pythonpython-datamodel

When where and how can i change the __class__ attr of an object?


I'd like to be able to do:

>>> class a(str):
...     pass
...
>>> b = a()
>>> b.__class__ = str
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types

Solution

  • I've solved it in this way:

    >>> class C(str):
    ...     def __getattribute__(self, name):
    ...         if name == '__class__':
    ...             return str
    ...         else:
    ...             return super(C, self).__getattribute__(name)
    ...         
    >>> c = C()
    >>> c.__class__
    <type 'str'>