Down casting Python objects
gagsl-py2 at yahoo.com.ar
Wed Mar 10 08:04:04 CET 2010
En Tue, 09 Mar 2010 18:26:52 -0300, Andrey Fedorov <anfedorov at gmail.com>
> So I have `x', a instance of class `Foo'. I also have class `Bar', a
> extending `Foo' with a couple of methods. I'd like to "down cast" x as
> efficiently as possible. Is it OK to just set `x.__class__ = Bar' and
> things to work OK in all major versions of CPython?
If the assignment x.__class__ = Bar succeeds, yes, that's enough. But you
may not be able to reassign __class__ in some cases (e.g. Foo defines
__slots__ but Bar doesn't, so you have a layout conflict).
Of course, you always have to make sure Bar invariants hold on this
I must ask, why you didn't create a Bar instance in the first place?
More information about the Python-list