Attaching Additional Methods to Existing Python Objects
In Python, it's generally not advisable to modify the methods of existing objects, but in certain situations, it may be necessary. This article explores how to add methods to instances after they have been created, highlighting the distinction between functions and bound methods.
Understanding Function vs. Bound Method
In Python, functions are unbound, while bound methods are associated with a specific instance. When a bound method is called, the instance is automatically passed as the first argument. This binding occurs when the method is defined in the class definition.
Updating Class-Level Methods
Modifying methods defined at the class level is straightforward. You can simply assign a new function to the method attribute of the class:
class A: def bar(self): print("bar") A.fooFighters = fooFighters
This change applies to all instances of the class, including existing ones.
Adding Instance-Specific Methods
Attaching methods to individual instances is more complex. Assigning a function directly to an attribute of an instance does not create a bound method, resulting in an error when called with zero arguments.
To create a bound method for a single instance, we can use the MethodType function from the types module:
import types a.barFighters = types.MethodType(barFighters, a)
Now, when a.barFighters() is called, the method is bound to the a instance, and it can be invoked without any additional arguments.
Preserving Instance Isolation
It's important to note that modifying instance-specific methods will not affect other instances of the same class. Each instance maintains its own set of attributes, including methods.
The above is the detailed content of How Can I Add New Methods to Existing Python Objects?. For more information, please follow other related articles on the PHP Chinese website!