Adding method dynamically in Python

Here is a good answer in SO:

>> class Dog():
… def __init__(self, name):
… self.name = name

>>> skip = Dog(‘Skip’)
>>> spot = Dog(‘Spot’)
>>> def talk(self):
… print ‘Hi, my name is ‘ + self.name

>>> Dog.talk = talk # add method to class
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk()
Hi, my name is Spot
>>> del Dog.talk # remove method from class
>>> skip.talk() # won’t work anymore
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: Dog instance has no attribute ‘talk’
>>> import types
>>> f = types.MethodType(talk, skip, Dog)
>>> skip.talk = f # add method to specific instance
>>> skip.talk()
Hi, my name is Skip
>>> spot.talk() # won’t work, since we only modified skip
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AttributeError: Dog instance has no attribute ‘talk’

So it looks like adding method to class is simple:

class.method = method

I’ve been using the types approach, it actually makes code harder to understand or maintain.

Advertisements
Adding method dynamically in Python