[Tutor] Transforming object into subclass instance

Kent Johnson kent37 at tds.net
Sun Oct 30 19:21:27 CET 2005

Jan Eden wrote:
> Now my question is: How can I turn an object of class X into an
> object of either class Y or Z while (retaining all the attributes
> defined so far).

This is easy, in fact - you can change the class of an instance by assigning to its __class__ attribute:
 >>> class F(object):
 ...   def p(self): print "F"
 >>> class G(object):
 ...   def p(self): print "G"
 >>> f=F()
 >>> f.p()
 >>> type(f)
<class '__main__.F'>
 >>> f.__class__ = G
 >>> f.p()
 >>> type(f)
<class '__main__.G'>
> I know I could solve the problem by using another switch statement -
> but is there consistent OOP solution for this problem?

I'm not sure I would call this solution OO or pretty but it does work.


More information about the Tutor mailing list