Changing the class of an instance

Huaiyu Zhu hzhu at knowledgetrack.com
Wed Jul 12 16:55:17 EDT 2000


On Wed, 12 Jul 2000 12:54:27 -0500, Paul Prescod <paul at prescod.net> wrote:
>Richard Tobin wrote:
>> 
>> Is it legal (it seems to work) to change the class of an object by
>> assigning to its __class__ attribute?  In particular for the case where
>> the new class is a subclass of the old.
>
>It language reference doesn't say. I think you're on your own but I
>wouldn't expect it to break soon. I also wouldn't expect it to work in
>JPython or maybe even Zope.
>

I guess the interesting question is: If __class__ is changed, is there any
trace of the older class left?  If it works in the module it is used, will
it break when it's imported by other modules?

I also find I need to do this a lot of time.  For example, when you read
something from a file, you want to return an object of a specific class
based on the content.  The easiest way to do it appears to be

class General:
   __init__(self, data):
       self.data = data
       if data is something:
           self.__class__ = Special1
       else:
           self.__class__ = Special2
	   
class Special1(General): pass

class Special2(General): pass

Huaiyu

-- 
Huaiyu Zhu                       hzhu at users.sourceforge.net
Matrix for Python Project        http://MatPy.sourceforge.net 



More information about the Python-list mailing list