faqts : Computers : Programming : Languages : Python : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

Entry

Is is possible to dynamically add methods to classes in Python?

Jun 24th, 2000 00:03
unknown unknown, Ken Seehof, Remco Gerlich


class some_class:
   pass
   
instance = some_class()

def some_method(self):
   print "Hello!"
   
some_class.method = some_method

instance.method()

eg:

>>> class C:
...  pass
...
>>> x = C()
>>> def f(self, z):
...  print self, z
...
>>> C.f = f
>>> x.f(12)
<__main__.C instance at 190d450> 12
>>>