Related: Convert Python Objects
I recently found out that Python allows you to change the instance class as follows:
class Robe: pass class Dress: pass r = Robe() r.__class__ = Dress
I am trying to find out if there is a case where the "transmutation" of such an object can be useful. I came across this in IDLE, and one thing I noticed is that assigning another class does not call the new class method __init__, although this can be done explicitly if necessary.
__init__
Almost every use case that I can think of will be better served by the composition, but I am encoding newb, so I know.;)
, Robe Dress. , , , .
Robe
Dress
, factory . :
class Base(object): pass def base_factory(): return Base() # in real code, this would probably be something opaque def Derived(Base): def __new__(cls): self = base_factory() # get an instance of Base self.__class__ = Derived # and turn it into an instance of Derived return self
Derived class __new__ base_factory, Base. factory - , , ( Base() super(Derived, cls).__new__(cls) , ).
__new__
base_factory
Base
Base()
super(Derived, cls).__new__(cls)
instance __class__ , Derived.__new__ Derived, , Derived.__init__ ( ).
__class__
Derived.__new__
Derived
Derived.__init__
, "" , . XMPP. XMPP XML- ( "stanzas" ) .
, DOM. , (, , ..). , , , DOM "" , , "get_author", "get_body" ..
, , , XML DOM. . -, XMPP , DOM, - - . -, , , , - , XMPP, .
, , , , ( ) CPython. , . , JIT- , CPython, !