downcasting problem
Tim Chase
python.list at tim.thechases.com
Mon Oct 25 10:38:42 EDT 2010
While a dirty hack for which I'd tend to smack anybody who used
it...you *can* assign to instance.__class__
>>> class A:
... def __init__(self, name):
... self.name = name
... def __str__(self): return self.name
...
>>> class B(A):
... def foo(self): print "I'm B: %r" % self.name
...
>>> class C(A):
... def foo(self): print "I'm C: %r" % self.name
...
>>> a = A("Alpha")
>>> print a
Alpha
>>> a.__class__
<class __main__.A at 0xb752d6bc>
>>> a.__class__ = B
>>> a.foo()
I'm B: 'Alpha'
>>> a.__class__ = C
>>> a.foo()
I'm C: 'Alpha'
If it breaks you get to keep all the parts :)
-tkc
More information about the Python-list
mailing list