acess class attribute in another file

前端 未结 4 1638
旧巷少年郎
旧巷少年郎 2021-01-24 21:18

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 __n         


        
4条回答
  •  渐次进展
    2021-01-24 21:51

    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.

提交回复
热议问题