简体   繁体   English

从另一个脚本访问函数内部的变量

[英]Accessing a variable inside a function from another script

comodin.py

def name():
    x = "car"

comodin_1.py

import comodin

print comodin.x

Error: 错误:

Traceback (most recent call last):
  File "./comodin_2.py", line 4, in <module>
    print comodin.x
AttributeError: 'module' object has no attribute 'x'

Is this possible? 这可能吗?

In the code you wrote, "x" doesn't exist in "comodin". 在您编写的代码中,“ comodin”中不存在“ x”。 "x" belongs to the function name() and comodin can't see it. “ x”属于函数name(),而comodin无法看到它。

If you want to access a variable like this, you have to define it at the module scope (not the function scope). 如果要访问这样的变量,则必须在模块作用域(而不是功能作用域)上定义它。

In comodin.py: 在comodin.py中:

x = "car"

def name():
    return x

In comodin_1.py: 在comodin_1.py中:

import comodin

print comodin.name()
print comodin.x

The last 2 lines will print the same thing. 最后两行将打印相同的内容。 The first will execute the name() function and print it's return value, the second just prints the value of x because it's a module variable. 第一个将执行name()函数并显示其返回值,第二个将仅显示x的值,因为它是一个模块变量。

There's a catch: you have to use the 'global' statement if you want to edit the value "x" from a function (add this at the end of comodin.py): 有一个陷阱:如果要从函数中编辑值“ x”(必须在comodin.py的末尾添加),则必须使用“ global”语句:

def modify_x_wrong():
    x = "nope"

def modify_x():
    global x
    x = "apple"

And in comodin_1.py: 在comodin_1.py中:

print comodin.name()  # prints "car"
comodin.modify_x_wrong()
print comodin.name()  # prints "car", once again
comodin.modify_x()
print comodin.name()  # prints "apple"

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

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