Python Dynamic Binding: Understanding Runtime Method Resolution
Explore dynamic binding in Python, a concept in object-oriented programming where method or attribute resolution occurs at runtime. Learn how dynamic binding, a key aspect of polymorphism, allows Python to determine the appropriate method or attribute based on the object's type or class hierarchy at runtime.
Python - Dynamic Binding
What is Dynamic Binding?
In object-oriented programming, dynamic binding is the process of resolving a method or attribute at runtime rather than at compile time. This concept is closely related to polymorphism, where different objects respond differently to the same method call based on their implementations.
The Python interpreter determines which method or attribute to invoke based on the object's type or class hierarchy at runtime, allowing for flexible and dynamic behavior.
Example of Dynamic Binding
The following example demonstrates dynamic binding in Python:
Example
class Shape:
def draw(self):
print("draw method")
class Circle(Shape):
def draw(self):
print("Draw a circle")
class Rectangle(Shape):
def draw(self):
print("Draw a rectangle")
shapes = [Circle(), Rectangle()]
for shp in shapes:
shp.draw()
Output
Draw a circle
Draw a rectangle
The draw()
method is dynamically bound to the corresponding implementation based on the object's type.
Duck Typing
Duck typing determines an object's suitability based on the presence of certain methods or attributes rather than its type. This allows for greater flexibility and code reuse in Python.
Dynamically typed languages like Python emphasize object behavior and interface over formal types. According to the "duck typing" concept, "If it walks like a duck and quacks like a duck, then it must be a duck."
Example of Duck Typing
The following example demonstrates duck typing:
Example
class Circle:
def draw(self):
print("Draw a circle")
class Rectangle:
def draw(self):
print("Draw a rectangle")
class Area:
def area(self):
print("Calculate area")
def duck_function(obj):
obj.draw()
objects = [Circle(), Rectangle(), Area()]
for obj in objects:
duck_function(obj)
Output
Draw a circle
Draw a rectangle
Traceback (most recent call last):
File "example.py", line 21, in
duck_function(obj)
File "example.py", line 17, in duck_function
obj.draw()
AttributeError: 'Area' object has no attribute 'draw'
The duck_function()
requires objects to have a draw()
method. It does not care about the specific types of the objects, promoting flexibility and code reuse.