Python 变量作用域和 .var
Python Variable Scope and .var
在 SaltyCraneBlog (http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/#c7900) 上,我正在阅读 Python 中的变量范围,一切都非常简单,直到我找到设置全局变量的解决方法:
def ex8():
ex8.var = 'foo'
def inner():
ex8.var = 'bar'
print 'inside inner, ex8.var is ', ex8.var
inner()
print 'inside outer function, ex8.var is ', ex8.var
ex8()
让我失望的是 ex8.var 部分。这是一个属性吗?如果 var 是 ex8 的属性,那么 var 不需要先定义吗?可以在函数本身内调用函数的属性吗?
What's throwing me off is the ex8.var part. Is this an attribute?
是的。
If var is an attribute of ex8, wouldn't var need to be defined first?
没有。您可以随时在对象上设置属性,而无需预先声明它们(除非对象定义了阻止您这样做的特殊行为)。
Can a function's attributes be called within the function itself?
是的,可以从函数内部访问函数的属性。该函数是一个与其他对象类似的对象,您可以访问它的属性,就像您可以访问当前范围内可访问的任何其他对象一样。 (这里的属性不是 "called",因为它的值不是函数;它只是您访问的一个值。)
正如您链接到的评论所提到的,这段代码所做的并不一定是一件好事。正如该博客 post 中提到的,Python 3 包含一个 nonlocal
关键字,消除了对此类 hackery 的需求。即使在 Python 2 中,发现自己处于需要诉诸此类技巧的情况也不常见。
在 SaltyCraneBlog (http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/#c7900) 上,我正在阅读 Python 中的变量范围,一切都非常简单,直到我找到设置全局变量的解决方法:
def ex8():
ex8.var = 'foo'
def inner():
ex8.var = 'bar'
print 'inside inner, ex8.var is ', ex8.var
inner()
print 'inside outer function, ex8.var is ', ex8.var
ex8()
让我失望的是 ex8.var 部分。这是一个属性吗?如果 var 是 ex8 的属性,那么 var 不需要先定义吗?可以在函数本身内调用函数的属性吗?
What's throwing me off is the ex8.var part. Is this an attribute?
是的。
If var is an attribute of ex8, wouldn't var need to be defined first?
没有。您可以随时在对象上设置属性,而无需预先声明它们(除非对象定义了阻止您这样做的特殊行为)。
Can a function's attributes be called within the function itself?
是的,可以从函数内部访问函数的属性。该函数是一个与其他对象类似的对象,您可以访问它的属性,就像您可以访问当前范围内可访问的任何其他对象一样。 (这里的属性不是 "called",因为它的值不是函数;它只是您访问的一个值。)
正如您链接到的评论所提到的,这段代码所做的并不一定是一件好事。正如该博客 post 中提到的,Python 3 包含一个 nonlocal
关键字,消除了对此类 hackery 的需求。即使在 Python 2 中,发现自己处于需要诉诸此类技巧的情况也不常见。