, 1 min read
Metaclass programming in Python
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.