[Tutor] Dynamic Method Creation

Chris Fuller cfuller084 at thinkingplanet.net
Thu Jul 10 19:38:46 CEST 2008

On Thursday 10 July 2008 09:09, George Flaherty wrote:
> Hello,
> I am trying to port over some old code from Ruby into Python.  In my old
> ruby code I had a UnitTest class that created a bunch of test methods (i.e.
> def test_MyTestFunction) dynamically through the ruby method
> define_method(http://www.ruby-doc.org/core/classes/Module.html#M000396).
> This functionally allowed me to create any number of methods dynamically
> within a particular class. My problem is I have never done this nor can
> find any examples of this within python and I am pretty sure python can
> handle this?
> If anyone could point me in the right direction?
> thanks
> -george

If you have an existing class, you can bind new methods to it by simply using 
>>> class A:
...   pass
>>> setattr(A, 'x',lambda self: 'foo')
>>> a=A()
>>> a.x()
>>> class B(A):
...  pass
>>> b=B()
>>> b.x()

You can also use new.classobj() to create arbitrary classes on-the-fly.  See 
the documentation for the  new module, and google "python metaclasses"


More information about the Tutor mailing list