How do you make issubclass work

Peter Otten __peter__ at web.de
Sat Sep 11 03:08:37 EDT 2004


Nathan Bullock wrote:

> Okay I have two files:
> 
> a.py:
> -----
> class cla_a(object): pass
> 
> class cla_c(object): pass
> 
> if __name__ == "__main__":
>   mod = __import__("b")
# why not
import b as mod

>   attr = getattr(mod, "cla_b")

# why not
attr = mod.cla_b

>   print issubclass(attr, cla_a)
>   print issubclass(cla_c, cla_a)
> -----
> 
> and b.py:
> -----
> from a import cla_a
> 
> class cla_b(cla_a): pass
> -----
> 
> now if I do 'python a.py'
> it gives me:
> False
> True

Should be:
True
False
 
> Why is cla_b a subclass and not cla_c?

Here you have it right again.

That you have two different modules does not affect the class hierarchy.
Y is a subclass of X if X can be found in the inheritance tree of Y, i. e.
occurs directly in Y's bases

>>> class X: pass
...
>>> class Y(X): pass
...
>>> issubclass(Y, X)
True

or indirectly in the bases' bases:

>>> class X: pass
...
>>> class Intermediate(X): pass
...
>>> class Y(Intermediate): pass
...
>>> issubclass(Y, X)
True

On the other hand it is not sufficient for a subclass relationship when two
classes share a common ancestor:

>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(A): pass
...
>>> issubclass(B, C), issubclass(C, B)
(False, False)

So you can think of subclasses as children and grandchildren, but not as
cousins. 

[As modules are cached, subsequent imports of the same module yield the same
module instance. Therefore the same classes (cla_a is cla_a == True) are
seen by all parts of a program and it (normally) doesn't matter in what
module a class is defined.]

Peter






More information about the Python-list mailing list