Wednesday, December 21st, 2005

Metaclass programming in Python

Filed under: — Daniel Lemire @ 10:58

I’m a few years behind, but while I knew you could modify classes in Python, it turns out you can do it conveniently as of Python 2.2.

Here’s how you can dynamically create a class:
>>> from new import classobj
>>> Foo2 = classobj('Foo2',(),{"mymethod":lambda self,x: x})
>>> Foo2().mymethod(2)
2

Once the class has been created, you can easily modify it as well:

>>> setattr(Foo2,'anothermethod',lambda self,x: 2*x)
>>> Foo2().anothermethod(2)
4

I recall that I found ways to achieve the same result by manipulating directly class objects, but this is much neater.

You can even dynamically change the class of an object:
>>> t.__class__=classobj('newFoo2', (Foo2,), {"supermethod":lambda self,x: 5*x})
>>> t.supermethod(2)
10

That’s pretty satisfying.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Warning: When entering a long comment, please ensure that you make copy of your text prior to submitting it. If the server should fail or if you hit a bug, you might lose your work. I am not responsible for your lost effort.

To spammers: I carefully review every single post and make sure that spam gets deleted. You are wasting your time if you are manually entering spam using this form. Read my terms of use to see what I consider to be abusive.

Example: I + II + IX= XII. Yes, you have to enter a roman numeral. (Answer must be in upper case.)

« Blog's main page

30 queries. 1.093 seconds. Valid XHTML

Powered by WordPress

Subscribe to this blog in a reader or by Email.