Method Invocation Patterns
Direct Method Calling
The most common and straightforward method of invoking methods in Python:
class Robot:
def move_forward(self, steps):
print(f"Moving {steps} steps forward")
def rotate(self, degrees):
print(f"Rotating {degrees} degrees")
## Direct method calling
robot = Robot()
robot.move_forward(5)
robot.rotate(90)
Method Chaining
Allows multiple method calls in a single line:
class StringProcessor:
def __init__(self, text):
self.text = text
def uppercase(self):
self.text = self.text.upper()
return self
def strip(self):
self.text = self.text.strip()
return self
def get_result(self):
return self.text
## Method chaining
result = StringProcessor(" hello world ").strip().uppercase().get_result()
Indirect Method Calling
Using getattr()
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
calc = Calculator()
method_name = "add"
method = getattr(calc, method_name)
result = method(10, 5)
Using callable()
def check_method_exists(obj, method_name):
return hasattr(obj, method_name) and callable(getattr(obj, method_name))
class Vehicle:
def start_engine(self):
print("Engine started")
car = Vehicle()
print(check_method_exists(car, "start_engine")) ## True
Method Invocation Flow
graph TD
A[Method Invocation] --> B[Direct Call]
A --> C[Chained Call]
A --> D[Indirect Call]
B --> E[Simple Method Execution]
C --> F[Sequential Method Execution]
D --> G[Dynamic Method Selection]
Advanced Invocation Techniques
Technique |
Description |
Use Case |
Reflection |
Dynamic method calling |
Plugin systems |
Decorators |
Method modification |
Logging, timing |
Descriptors |
Custom method behavior |
Property implementation |
Bound vs Unbound Method Calls
class Greeter:
def say_hello(self, name):
return f"Hello, {name}!"
## Bound method
greeter = Greeter()
bound_method = greeter.say_hello
print(bound_method("Alice"))
## Unbound method
unbound_method = Greeter.say_hello
print(unbound_method(greeter, "Bob"))
LabEx Pro Tip
Mastering different method invocation patterns enhances your Python programming flexibility and enables more dynamic code design.
Key Takeaways
- Multiple ways to call methods exist
- Method chaining provides concise code
- Reflection allows dynamic method selection
- Understanding method binding is crucial
- Choose the right invocation pattern for your use case