Accessing Instance Methods
In Python, objects have two types of methods: functions and bound methods. Bound methods are associated with a specific instance, and they pass the instance as the first argument when called. Functions, on the other hand, are unbound and can be modified at any time.
To illustrate the difference:
def foo(): print("foo") class A: def bar(self): print("bar") a = A() print(foo) # <function foo at 0x00A98D70> print(a.bar) # <bound method A.bar of <__main__.A instance at 0x00A9BC88>>
Adding Methods to Class Definitions
You can modify class definitions to add new methods for all instances. For example, the following adds a fooFighters method to the A class:
def fooFighters(self): print("fooFighters") A.fooFighters = fooFighters a2 = A() a2.fooFighters() # fooFighters # Also affects previously defined instances a.fooFighters() # fooFighters
Adding Methods to Single Instances
Adding methods to individual instances is more complex. The following attempt fails because the function is not bound to the instance:
def barFighters(self): print("barFighters") a.barFighters = barFighters a.barFighters() # TypeError: barFighters() takes exactly 1 argument (0 given)
To bind the function, use the MethodType function from the types module:
import types a.barFighters = types.MethodType(barFighters, a) a.barFighters() # barFighters # Other instances unaffected a2.barFighters() # AttributeError: A instance has no attribute 'barFighters'
Further exploration of descriptors and metaclass programming provides more advanced techniques for manipulating object methods.
The above is the detailed content of How Do I Add and Access Instance Methods in Python?. For more information, please follow other related articles on the PHP Chinese website!