Using variables inside a function in another pytho

2019-08-04 12:19发布

i cant seem to make this work.

I have 2 python files, lets say a.py and b.py

in a.py is this:

def foo():
    global name
    name = "foo"
    import b
    b.bar()

if __name__ == "__main__":
    foo()

in b.py this:

import a

def bar():
    name = a.name
    print(name)

I have three different question in relation to this code:

  1. Why do i get the error: AttributeError: 'module' object has no attribute 'name' I know for certain that b.py cant access the variable defined in the function in b.py but how do i solve this?
  2. does global in this case changes anything? if not, why?
  3. i tried doing name = a.foo.name instead of name = a.name but this doesnt do the trick either and gives me: AttributeError: 'function' object has no attribute 'name', is this even practicable in any case and what did i do wrong?

Thanks for taking the time and sorry if this seems obvious to some of you, i'am still getting into this.

1条回答
Viruses.
2楼-- · 2019-08-04 13:22

Scripts aren't modules. Its something of a mind bender but when you run python3 a.py, a.py isn't a module (or more properly, its a module named __main__) and it will be reloaded when you import.

Suppose I have c.py

print('hello')
if __name__=="__main__":
    import c

When I run it I get

hello
hello

To illustrate with your example, if I change b.py to

import __main__

def bar():
    name = __main__.name
    print(name)

It works. But only kindof because if somebody imports a you've still got two modules and two copies of the variable.

If you want shared data, they have to be in imported modules, not top level scripts. When I want shared data, I create a separate module that doesn't import anything (or only imports from the standard library) and it is either empty or has defaults for the variables I want to share.

查看更多
登录 后发表回答