acess class attribute in another file

前端 未结 4 1662
旧巷少年郎
旧巷少年郎 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 22:00

    Yeah, I can see how this can be a little confusing but it is basically a question of namespaces along with the distinction that the __main__ namespace is not considered as part of the list of imported modules. This allows the file that is the point of execution (and thus occupying the __main__ namespace) to also be imported as a module. On the other hand, if the same module is imported more than once, the interpreter will simply let all the different imports point to the same memory location

    Because of this, in the code you are showing above, you actually have two distinct versions of A: you have __main__.A and you have __main__.t2.t1.A. The second one comes about because __main__is importing t2 which in turn is importing t1 as a module.

    When you are running t2.f(), you are setting __main__.t2.t1.A.flag = True and then printing it. Subsequently, when you call print(A.flag), you are printing the value in __main__.A.flag, which was never changed.

    I hope that makes at least a little sense.

    A friend of mine always said that computer science is an experimental science. Let's invoke the debugger.

    I add a pdb.set_trace() to the execution and t1.py now looks like this:

    #!/usr/bin/python
    import t2
    
    class A:
            flag = False
    
    if __name__ == "__main__":
        import pdb; pdb.set_trace()
        t2.f()
        print(A.flag)
    

    And this is what we get:

    $ python t1.py
    > /Users/martin/git/temp/t1.py(9)()
    -> t2.f()
    (Pdb) A
    
    (Pdb) t2.t1.A
    
    (Pdb) 
    

    Please note that the A have separate memory locations associated.

提交回复
热议问题