Dynamically adding methods to objects in Python

The trick is that you have to add the function to the class not the instance to see how, run your interpreter and write these:

class test:
	def __init__(self):
		self.yes = "Hello Python!"
 
def a(self):
	print self.yes
 
t = test()
t.b = a
t.b()

When this runs, you get:

Traceback (most recent call last):
File “ “, line 1, in
t.b()
TypeError: b() takes exactly 1 argument (0 given)

To fix this, you will have to assign the function a to the class itself (test) not the instance (t) like:

test.b = a
t = test()
t.b()

Python is fun :)

Leave a Comment for Dynamically adding methods to objects in Python