Adding new methods to new-style classes dynamically

John Machin sjmachin at lexicon.net
Thu May 5 05:10:25 EDT 2005


Max Derkachev wrote:
[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
>
>
> Of course, I can do
> A.foo = some_executable_object
> But that does help when a dynamic method name is needed.
> Another option is:
> exec('A.%s = %s'%('foo', 'some_executable_option'))
> But I don't like eval'ling things :)
>
> Is there other way to add/change methods to new-style classes
> dynamically?

Ever considered setattr()? Not only does it appear to do the job but
also it avoids those __make__your__eyes__bleed__ double underscores.

>>> class A(object):
...    pass
...
>>> A.__dict__['foo'] = 123
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>> setattr(A, 'foo', 123)
>>> A.foo
123
>>>>>> def bar(self):
...    print 'bar bar blog ship'
...
>>> setattr(A, 'bar', bar)
>>> eh = A()
>>> eh.bar()
bar bar blog ship
>>>

HTH,
John




More information about the Python-list mailing list