Down casting Python objects

Gabriel Genellina 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>  
escribió:

> So I have `x', a instance of class `Foo'. I also have class `Bar', a  
> class
> 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  
> expect
> 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  
particular instance...

I must ask, why you didn't create a Bar instance in the first place?

-- 
Gabriel Genellina




More information about the Python-list mailing list