modifying __class__

Evan Klitzke evan at yelp.com
Fri Oct 26 09:49:37 CEST 2007


On 10/26/07, Piyush Jain <piyush.subscription at gmail.com> wrote:
> Hi,
> Itis possible to change the class of an object by assigning new value to
> __class__
> Is it possible to call my module when it is done.
> For example,
> object = ClassA()
>
> object.__class__ = classB # I want to call my method when this statement is
> executed.

Here's an example of how to do this:

class A(object):
        def __init__(self):
                self._class = A

        def getclass(self):
                return self._class

        def setclass(self, x):
                print 'setting __class__ to %s' % x
                self._class = x

        __class__ = property(getclass, setclass)

class B(object):
        pass

if __name__ == '__main__':
        a = A()
        print 'Running a.__class__ = B'
        a.__class__ = B

        print 'a.__class__ = %s' % a.__class__

> I want to do it in a general way. For ex. , whenever __class__ is changed
> for any object instance (of different classes), my own function is called.
> How should I do it ?

I think you can do this using a metaclass, and then have all of your
classes inherit from the metaclass rather than object, but I don't
really have any experience doing this.

-- 
Evan Klitzke <evan at yelp.com>



More information about the Python-list mailing list