Python 类中实例变量和类变量还有类内定义的函数,它们之间作用域是怎么样的,变量之间的关系是怎么样( 二 )

class A: a = 42 b = list(a + i for i in range(10))需要注意的是block与scope的细微差别,考虑如下代码:Python 3.3.3 (default, Dec 10 2013, 18:43:00) on darwinType "help", "copyright", "credits" or "license" for more information.\u0026gt;\u0026gt;\u0026gt; class Test:... a = range(10)... b = ...\u0026gt;\u0026gt;\u0026gt; Test\u0026lt;class \u0026#39;__main__.Test\u0026#39;\u0026gt;\u0026gt;\u0026gt;\u0026gt; Test.b\u0026gt;\u0026gt;\u0026gt; class Test:... a = 10... b = ...Traceback (most recent call last): File "\u0026lt;stdin\u0026gt;", line 1, in \u0026lt;module\u0026gt; File "\u0026lt;stdin\u0026gt;", line 3, in Test File "\u0026lt;stdin\u0026gt;", line 3, in \u0026lt;listcomp\u0026gt;NameError: global name \u0026#39;a\u0026#39; is not definedWHY?The comprehension consists of a single expression followed by at least onefor clause and zero or more for or if clauses.In this case, the elements of the new container are those that would be producedby considering each of the for or if clauses a block,nesting from left to right, and evaluating the expression to produce an elementeach time the innermost block is reached.
【Python 类中实例变量和类变量还有类内定义的函数,它们之间作用域是怎么样的,变量之间的关系是怎么样】 Note that the comprehension is executed in a separate scope, so names assignedto in the target list don’t “leak” in the enclosing scope.


推荐阅读