简体   繁体   English

python:在不同模块的函数中访问变量

[英]python: Accessing variable in functions in different modules

I've distilled down what I'm trying to do to the simplest form.我已经将我正在尝试做的事情提炼成最简单的形式。 I have a one module (prog1.py) that runs fine.我有一个运行良好的模块(prog1.py)。 A function in prog1.py accesses a variable (yy) OK without an error. prog1.py 中的 function 访问变量 (yy) OK 没有错误。

#prog1.py 
def func():
    print (yy)
    return()

def main(yy):
    print(yy)
    func()
    return()

#-----------------------------------------------
if __name__ == '__main__':     
    yy = 200
    main(yy)

When I import that module into another module (prog2.py) the same function cannot access the variable (yy).当我将该模块导入另一个模块(prog2.py)时,相同的 function 无法访问变量(yy)。

#prog2.py
import prog1
yy = 200
prog1.main(yy)

I get:我得到:

name 'yy' is not defined in line 3 in func.名称 'yy' 未在 func 的第 3 行中定义。

What is the "correct" (python) way to do this?执行此操作的“正确”(python)方法是什么?

Issue is in func :问题在于func

def func():
    print (yy)
    return()

Line print (yy) tries to access yy , but if __name__ == '__main__': will not be true for that module ( __name__ will be prog1 not __main__ ), hence it will not go inside if :print (yy)尝试访问yy ,但if __name__ == '__main__':不适用于该模块( __name__将是prog1而不是__main__ ),因此它不会在 go 内部if

if __name__ == '__main__':     
    yy = 200
    main(yy)

Hence yy will not be defined.因此yy不会被定义。

Read more about if __name__ == '__main__': in this question .阅读更多关于if __name__ == '__main__':在这个问题中。


According to what you have mentioned in the comments:根据您在评论中提到的内容:

#prog1.py

yy = 'prog1 yy'


def func():
    print(yy)


def main(yy):
    print(yy)
    func()


if __name__ == '__main__':
    yy = 200
    main(yy)
# prog2.py

import prog1


yy = 200
prog1.main(yy)

Run:跑:

python prog2.py

Output: Output:

200
prog1 yy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM