In Python (and in OOP in general), binding refers to the association between a method call and the method’s definition. The difference between static binding and dynamic binding revolves around when this association happens—at compile-time or runtime.
1. Static Binding (Early Binding) #
- Definition: The method call is resolved at compile-time.
- Typical for: Instance methods of a class when no overriding occurs or for private/final methods in languages like Java.
- In Python, methods that do not involve inheritance or overriding behave like static binding.
- Key point: Faster, less flexible.
Example:
filename.python
class Employee:
def work(self):
print("Employee working")
emp = Employee()
emp.work() # Static binding: emp is known at definition
Here, emp.work() is bound to Employee.work() at the time the code is written.
2. Dynamic Binding (Late Binding) #
- Definition: The method call is resolved at runtime, based on the actual object type.
- Typical for: Polymorphism / method overriding.
- Python uses dynamic binding by default because it’s a dynamically typed language.
Example:
filename.python
class Employee:
def work(self):
print("Employee working")
class Manager(Employee):
def work(self): # overrides work
print("Manager managing team")
def start_work(emp):
emp.work() # Dynamic binding: method resolved at runtime
e = Employee()
m = Manager()
start_work(e) # Employee working
start_work(m) # Manager managing team
Here, emp.work() is dynamically bound to the actual object (Employee or Manager) at runtime.
Key Differences #
| Feature | Static Binding | Dynamic Binding |
|---|---|---|
| When resolved | Compile-time | Runtime |
| Flexibility | Less flexible | More flexible (supports polymorphism) |
| Performance | Faster | Slightly slower |
| Typical use | Non-overridden methods | Overridden methods in inheritance |
| Python default | Rare (mostly private attributes) | Yes (most method calls) |
Practical Use Case #
In a reporting system I built:
- Static binding was used for helper methods that didn’t change per report type.
- Dynamic binding was used for
generate_report()methods overridden in subclasses (MonthlyReport,AnnualReport). This allowed the system to callgenerate_report()on any report object without knowing its type beforehand—classic runtime polymorphism.
