Class.__class__ magic trick help

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Aug 20 14:21:53 EDT 2012


On Mon, 20 Aug 2012 11:01:36 -0700, Massimo Di Pierro wrote:

> I discovered I can do this:
> 
>     class A(object): pass
>     class B(object):
>         __class__ = A # <<<< magic

Why do you think that's magic?

 
>     b = B()
>     isinstance(b,A) # returns True (as if B derived from A)

b.__class__ is A, so naturally isinstance(b, A) will return True.

>     isinstance(b,B) # also returns True

type(b) is B, so naturally isinstance(b, B) will return True.


> I have some reasons I may want to do this (I an object with same methods
> as a dict but it is not derived from dict and I want
> isinstance(x,dict)==True to use it in place of dict in some other code).

Be aware that some parts of Python will insist on real dicts, not just 
subclasses or fake dicts.


-- 
Steven



More information about the Python-list mailing list