Class mutation

Markus Schaber markus at schabi.de
Thu Sep 27 08:59:34 EDT 2001


Hi,

Dale Strickland-Clark <dale at riverhall.NOSPAMco.uk> schrub:

> "Thomas Heller" <thomas.heller at ion-tof.com> wrote:
>>"Dale Strickland-Clark" <dale at riverhall.NOSPAMco.uk> wrote in message
>>news:8626rt838oe59d1njrtrisccm0oe02shvf at 4ax.com...
>>> Lets say we have a class 'Job' and another class derived from that
>>> 'ActiveJob'.
>>>
>>> I'd like to mutate a Job object into the extended ActiveJob object
>>> without re-assigning all the attributes.

>>job.__class__ = ActiveJob

> Interesting but looks doomed (See other comment.).

But it exactly does what you want. It assigns the new class to your job 
object.

Every object in an object oriented language has a backpointer to its 
class descriptor. In Python, this is an ordinary attribute called 
__class__ (the double underscores on both ends indicate a python 
internal data). And as classes themselves are just objects, no one 
prohibits you from just manipulating this reference to point to another 
class. This way, the object grabs all methods and class variables. The 
objects variables stay as before (means when ActiveJob objects have 
additional attributes, you have to add them by hand).

markus

-- 
"The strength of the Constitution lies entirely in the determination of 
each citizen to defend it. Only if every single citizen feels duty 
bound to do his share in this defense are the constitutional rights 
secure." -- Albert Einstein



More information about the Python-list mailing list