Good day to all.
Some time ago I'd been playing with a framework which uses dynamic
class creation havily. Say, I could do:
class A:
pass
# I method name is dynamic
meth_name = 'foo'
#method code can also be dynamic - any executable object will be good
enough
func = lambda self: self.__class__. __name__
A.__dict__[meth_name] = func
a = A()
print a.foo()[color=blue][color=green]
>> A[/color][/color]
# methods could be added/changed at runtime, without re-instantination
A.__dict__[meth_name] = lambda self: type(self)
print a.foo()[color=blue][color=green]
>> <type 'instance'>[/color][/color]
#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)[color=blue][color=green]
>>Traceback (most recent call last):
>> File "<interacti ve input>", line 1, in ?
>>TypeError: object does not support item assignment[/color][/color]
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_executabl e_option'))
But I don't like eval'ling things :)
Is there other way to add/change methods to new-style classes
dynamically?
Some time ago I'd been playing with a framework which uses dynamic
class creation havily. Say, I could do:
class A:
pass
# I method name is dynamic
meth_name = 'foo'
#method code can also be dynamic - any executable object will be good
enough
func = lambda self: self.__class__. __name__
A.__dict__[meth_name] = func
a = A()
print a.foo()[color=blue][color=green]
>> A[/color][/color]
# methods could be added/changed at runtime, without re-instantination
A.__dict__[meth_name] = lambda self: type(self)
print a.foo()[color=blue][color=green]
>> <type 'instance'>[/color][/color]
#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)[color=blue][color=green]
>>Traceback (most recent call last):
>> File "<interacti ve input>", line 1, in ?
>>TypeError: object does not support item assignment[/color][/color]
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_executabl e_option'))
But I don't like eval'ling things :)
Is there other way to add/change methods to new-style classes
dynamically?
Comment