Bypassing __setattr__ for changing special attributes

Ziga Seilnacht ziga.seilnacht at gmail.com
Tue Feb 20 02:18:02 EST 2007


George Sakkis wrote:
> I was kinda surprised that setting __class__ or __dict__ goes through
> the __setattr__ mechanism, like a normal attribute:
>
> class Foo(object):
>     def __setattr__(self, attr, value):
>         pass
>
> class Bar(object):
>     pass
>
> >>> f = Foo()
> >>> f.__class__ = Bar
> >>> print f.__class__ is Foo
> True
>
> Is there a way (even hackish) to bypass this, or at least achieve
> somehow the same goal (change f's class) ?
>
> George

>>> object.__setattr__(f, '__class__', Bar)
>>> f.__class__ is Bar
True

Ziga




More information about the Python-list mailing list