python - python中类 block 和函数 block 的区别

标签 python

代码1

x = 0

class Foo:
    print(x)
    x = 1
    print(x)

print(x)

结果 1

0
1
0

代码2

x = 0

def foo():
    print(x)
    x = 1
    print(x)

foo()

结果2

UnboundLocalError: local variable 'x' referenced before assignment.

为什么 x 可以在 class block 中引用来自两个命名空间的对象?
我不明白为什么 Code 1 没有抛出 UnboundLocalError
函数和类之间的不一致困扰着我。


更新:

看完Python Docs几次,我仍然无法理解范围规则。

The following are blocks: a module, a function body, and a class definition. ...[skip]...

If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.

最佳答案

x = 0

class Foo:
    print(x)   # Foo.x isn't defined yet, so this is the global x
    x = 1      # This is referring to Foo.x
    print(x)   # So is this

print(x)

x = 0

def foo():
    print(x)   # Even though x is not defined yet, it's known to be local
               # because of the assignment
    x = 1      # This assignment means x is local for the whole function
    print(x)

foo()

关于python - python中类 block 和函数 block 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12810426/

相关文章:

python - wxPython StaticText Widget 字体

python - 如何在 2016.1 Intellij IDEA/Python 社区版 5.1.145.45 中启用 python 文档字符串插入

python - 如何在 matplotlib finance 中保存烛台图表

python - 从 Tensorflow 变量中提取值

python - 从另一个对象访问结构指针时遇到问题

python - 正则表达式在 python 中无法正常工作

python - rgb 到 yuv 转换和访问 Y、U 和 V channel

python - 如何阻止方法内部的警告

python - 将 pandas.Series.value_counts 返回的系列转换为字典

python - Json.dump 失败并出现 'must be unicode, not str' TypeError