Happy fun python snippit

An example of how to add a method to a class, and how to add to just an instance of object.


import new

  1. add method to all object of a class

class test:
pass

def monkey(self):
print “eek”

tta = test()
ttb = test()
tta.class.monkey = monkey
print ”%r” % tta.monkey
print ”%r” % ttb.monkey

  1. add to one instance

class test2:
pass

tt2a = test2()
tt2b = test2()

tt2a.monkey = new.instancemethod(monkey, tt2a, tt2a.class)

print ”%r” % tt2a.monkey
# this will cause an exception
print ”%r” % tt2b.monkey

Aug. 25, 2003 (5 years, 4 months ago) | Tags: python