Structure:
JavaScript
x
4
1
package/
2
m1.py
3
m2.py
4
m1.py
:
JavaScript
1
9
1
class A:
2
pass
3
4
5
if __name__ == '__main__':
6
from m2 import B
7
8
print(issubclass(B, A))
9
m2.py
:
JavaScript
1
6
1
from m1 import A
2
3
4
class B(A):
5
pass
6
I don’t now why I get false while I think it’s obviously true when I run m1.py. My python version is python3.5.2.
Advertisement
Answer
Wellcome to the world of modules and namespaces!
Here is what happens:
In module m2, you import A from module m1. So you create a class m2.A
as a reference to class m1.A
. It happens to have the same definition as __main__.A
, but they are different objects, because the main module is named __main__
and not m1
. Then in module __main__
you create a class __main__.B
as a reference to class m2.B
To better understand what happens here, I have added some code to m1:
JavaScript
1
9
1
2
print(issubclass(B, A))
3
4
import m1
5
import m2
6
print(A == m1.A, m1.A == m2.A)
7
print(B == m2.B)
8
print(issubclass(B, m2.A), issubclass(B, m1.A))
9
The output is:
JavaScript
1
5
1
False
2
False True
3
True
4
True True
5
Proving that B is indeed a subclass of m1.A
but not of __main__.A
.