김영석 김영석 - 4 months ago 8
Python Question

acess class attribute in another file

I'm new to python.

I have a question about accessing attribute in class

t1.py

#!/usr/bin/python
import t2

class A:
flag = False

if __name__ == "__main__":
t2.f()
print(A.flag)


t2.py

#!/usr/bin/python
import t1

def f():
t1.A.flag = True
print(t1.A.flag)


excute Result:

# ./t1.py
True
False


I expect that result has to be True, True.

Are A.flag in t1.py and t1.A.flag in t2.py diffrent?

What happends in python when excute this code?

Thank you.

Answer

When you do

./t1.py

you're executing the t1.py file, but it's not executed as the t1 module. It's considered to be the __main__ module. (This is what that if __name__ == '__main__' line checks for.) That means that when this line:

import t1

in t2.py tries to import t1, Python starts executing the t1.py file again to create the t1 module. You end up with two versions of the A class, one being __main__.A and one being t1.A. The modification to t1.A doesn't do anything to __main__.A, because even though they came from the same code in the same file, they're not the same class.