Dec 10
Changing types in Python
Okay, so its another entry in my long-abandoned python tricks series.
First, lets take a look at a couple of classes:
class B(object): def foo(self): return '10' class A(object): def __init__(self): self.a='a' def foo(self): return '1'
The important part here is the (object) subclassing. This trick only works if you do that. Lets take alook at it in operation:
>>> a=A() >>> a <changetype.A object at 0x7f0f18dbf9d0> >>> a.__class__ <class 'A'> >>> a.a 'a' >>> a.foo <bound method A.foo of <changetype.A object at 0x7f0f18dbf9d0>> >>> a.foo() '1' >>> a.__class__=B >>> a.a 'a' >>> a.foo <bound method B.foo of <changetype.B object at 0x7f0f18dbf9d0>> >>> a.foo() '10' >>> isinstance(a, B) True
As you can see, I was able to override the foo() method with the one in the Beta class. As well, this only works on instanced objects. Now, what use is this you may ask? It is basically meta-programming. For 90% of programming tasks, meta-programming is not needed at all. But for that remaining 10%, you can do some seriously cool stuff, like changing the operation of a class during runtime, without modifying the class variables.
As a real-life example, I just finished writing a simplistic query parser. I realized I had forgetten to take into account price queries, so, I created a PriceToken class, that on instantiation, changes its own class to that of a TermToken. Otherwise, I would have had to rewrite about 100 lines of code to allow the use of a PriceToken. Pretty much useful because I’m lazy. But, yes, in Python, you can change the type of an object on the fly.
1 comment1 Comment so far
[...] Code – A member of CompSci.ca, he posts some interesting articles on computer science topics, like Python tricks and opinions on Canadian copyright [...]