Monday, 20 February 2012

Python __class__

Each value is an object, and therefore has a class (also called its type). It is stored as object.__class__.


> 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.