From LinkedIn Learning.
Pattern. Strategy:
What it types.MethodType ?
types.MethodType in Python is a utility function from the types module that allows you to bind a function as a method to an instance of a class. This can be especially useful when you want to add or replace methods dynamically for an object at runtime. Let's go over how it works and look at an example.
types.MethodType(function, instance)
- function: The function you want to bind to an instance.
- instance: The object (usually an instance of a class) to which you want to bind the function as a method.
When to Use types.MethodType
- Adding new methods to existing instances: Useful in scenarios where you need to modify the behavior of a particular instance without changing the class itself.
- Replacing methods dynamically: If you need to override or alter a method on a per-instance basis (e.g., for testing or specific instances only).
- Creating flexible or extensible objects: This can help in creating objects that can adapt their behavior after they are instantiated.
Example Usage
Suppose you have a class Person but want to dynamically add a new method to one specific instance:
Explanation of Example
- We defined a regular function say_hello outside the class Person.
- Using MethodType, we bind say_hello to the person instance, making it a method for just that instance.
- After binding, we can call person.say_hello() as if it was originally defined as part of the Person class, and it will have access to the self parameter (the person instance).
Key Points
- MethodType does not add the method to the class but to the specific instance.
- The self argument works correctly because MethodType binds the function to the instance.
Advanced Example: Replacing an Existing Method
In this example, the original greet method is replaced only for person. If you
create another Person instance, it will still use the original greet
method.
Using types.MethodType offers flexibility, especially for
cases where modifying the class itself isn’t desired or possible.
More info
Немає коментарів:
Дописати коментар