views:

62

answers:

2

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
A: 

Only classes that were defined with a class keyword could be used for __class__ attribute assignment:

>>> class C:
    pass

>>> class D:
    pass

>>> C().__class__ = D
>>>
SilentGhost
No it isn​'​t​.
Ignacio Vazquez-Abrams
That´s not what they say here:http://bytes.com/topic/python/answers/449635-assigning-self-__class__
Juanjo Conti
In fact, I think `__mro__` is the only read-only attribute there.
Ignacio Vazquez-Abrams
@Ignacio, @Juanjo: thanks corrected.
SilentGhost
I think this is not total true. You may have class A(str) and you cant assign A.
Juanjo Conti
A: 

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'>
Juanjo Conti