You Are Here Home > Dynamically adding methods to objects in Python
DirectorySync is a directory synchronizing and backup utility providing automated, real-time syncing and scheduled, configurable backups at an affordable price.

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 :)

Dynamically adding methods to objects in Python
Filed under: Python   Posted by: Codehead
Do you have any questions? ask here.




No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment