[英]Python variable scope issue
Python script: Python脚本:
def show(name):
def getName():
return _name
def setName(value):
_name = value
_name = ''
print('Input parameter: ', name)
print('Global variable: ', say_hello)
print('Change private variable: ', setName(name))
print('Get private variable: ', getName())
print('Private variable: ', _name)
print('Input parameter: ', name)
say_hello = 'hello'
show('Jim')
Output: 输出:
Input parameter: Jim
Global variable: hello Change
private variable: None
Get private variable:
Private variable:
Input parameter: Jim
Why doesn't the inner function change the value of _name
, yet the function show
can get the value of say_hello
? 内部函数为什么不更改_name
的值,而show
函数可以获取say_hello
的值? I know it's a variable scope problem, but I want to know some detail. 我知道这是一个可变范围的问题,但我想知道一些细节。
Assignments in functions are assigned in the functions local scope. 功能分配在功能本地范围内分配。 setName
assigns _name
in the local scope in setName
, the outer _name
is unaffected. setName
在setName
的本地范围内分配_name
,外部_name
不受影响。
In Python 2.X, it is possible to assign to the module global scope by using the global statement, but not to an outer local scope. 在Python 2.X中,可以使用global语句分配给模块全局范围,而不是外部局部范围。
Python 3.X adds the nonlocal
statement (see PEP-3104 for details if you are interested). Python 3.X添加了nonlocal
语句(如果您有兴趣,请参阅PEP-3104了解详细信息)。 In your example, nonlocal could be used in setName to assign to the outer local scope. 在您的示例中,可以在setName中使用nonlocal来分配给外部本地范围。
This blog post discusses variable scoping in Python with some nice examples and workarounds (see example 5 specifically). 这篇博客文章讨论了Python中的变量作用域,并提供了一些不错的示例和变通方法(具体请参见示例5)。
_name
is, in this case, local to the setName()
function, as every variable name is when assigned to in a function. 在这种情况下, _name
是setName()
函数的局部变量,因为每个变量名都是在函数中分配的。
Unless you have a global
statement, or in 3.x, a nonlocal
statement - which would help you in this case. 除非您有global
语句或在3.x中使用nonlocal
语句,否则在这种情况下会有所帮助。
Why not moving show
as a say_hello
method? 为什么不将show
作为say_hello
方法移动?
class SayHello(unicode):
_name = u""
def get_name(self):
return self._name
def set_name(self, value):
self._name = value
def show(self, name):
self.name = name
print(self, self.name)
name = property(get_name, set_name)
say_hello = SayHello('hello')
say_hello.show('Jim')
You should avoid using global variables if not strictly necessary. 如果非绝对必要,则应避免使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.