Adding new methods to new-style classes dynamically

Jack Diederich jack at performancedrivers.com
Thu May 5 12:38:37 EDT 2005


On Thu, May 05, 2005 at 01:35:09AM -0700, Max Derkachev wrote:
> Good day to all.
> 
> Some time ago I'd been playing with a framework which uses dynamic
> class creation havily. Say, I could do:
<snip>
> 
> #well, try this with the new-style class
> class A(object):
>     pass
> 
> # the new-style __dict__ is a dictproxy object
> A.__dict__[meth_name] = lambda self: type(self)
> >>Traceback (most recent call last):
> >>  File "<interactive input>", line 1, in ?
> >>TypeError: object does not support item assignment
> 
> Is there other way to add/change methods to new-style classes
> dynamically?

>>> import new
>>> dir(new)
['__builtins__', '__doc__', '__file__', '__name__', 'classobj', 'code', 'function', 'instance', 'instancemethod', 'module']
>>> def foo(self):
...   print "FOO!"
>>> A.foo = new.instancemethod(foo, None, A) # func, object, class
>>> A.foo
<unbound method A.foo>
>>> a = A()
>>> a.foo
<bound method A.foo of <__main__.A object at 0xb7e0b4cc>>
>>> a.foo()
FOO!

-jackdied





More information about the Python-list mailing list