Describing Polymorphism
- Dynamic binding is sometimes referred to as polymorphism in the context of inheritance
- Dynamic binding is the capability to use an instance without regard for its type
-
It is handled entirely through the attribute lookup process:
- Search for an attribute within the instance
- Search for an attribute within the class
- Search for an attribute within base classes
-
Static binding has the following attribute lookup process:
- Search for an attribute within the instance
-
Method overloading is an example of static binding
- This refers to optional parameters in Python
- Method overriding is an example of dynamic binding
Inheritance without Duck Typing
>>> class BadAccount(Account):
... def __init__(self, id, name):
... self.id = id
... self.name = name
... def inquiry():
... return 'bad account'
Inheritance with Duck Typing
>>> class BadAccount:
... def __init__(self, id, name):
... self.id = id
... self.name = name
... def inquiry():
... return 'bad account'
Details about Duck Typing
- In a statically typed language, we have to concept of adding
- However, only some types of objects can be added
- You won't be able to add different types of objects together
- In Python, classes are able to define what it means to be added
- For example,
a+b
is syntactic sugar for the__add__
method - Duck typing implies Python doesn't care about which class
a
belongs to - All it cares about is whether the call to the
__add__
method returns anything sensible - If not, a
TypeError
error will be raised typically - However, Python at least attempts to interpret
a + b
without checking whethera
andb
both belong to the same class - This is unlike many statically typed languages
References
Previous
Next