Adding new methods to new-style classes dynamically

M

Max Derkachev

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()# methods could be added/changed at runtime, without re-instantination
A.__dict__[meth_name] = lambda self: type(self)
print a.foo()
#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)

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?
 
M

Michele Simionato

Do you mean setattr?

setattr(A, meth_name, lambda self: type(self))


Michele Simionato
 
J

John Machin

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)

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.
.... pass
....
Traceback (most recent call last):
.... print 'bar bar blog ship'
....
HTH,
John
 
J

Jack Diederich

Good day to all.

Some time ago I'd been playing with a framework which uses dynamic
class creation havily. Say, I could do:
#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)
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
a = A()
a.foo
FOO!

-jackdied
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top