[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Down casting Python objects

Gabriel Genellina

3/10/2010 7:04:00 AM

En Tue, 09 Mar 2010 18:26:52 -0300, Andrey Fedorov <anfedorov@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