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.
推荐阅读
- 怎样成为一名合格的Python程序员?
- python 爬虫,咋获得输入验证码之后的搜索结果
- python的html5lib这个库咋使用啊我在网上也没有找到相关文档
- 零基础入门学习啥语言好
- Python3.4和3.5区别大么
- python 中 def_():...... return _有啥作用
- 新互联网网站用Java还靠谱么对比Php,Python,Ruby的话
- 30岁男,创业失败转行学python,是否很晚?也不好找工作?
- Python 的开发速度比 C#.net 或 Vb.net 更快吗?
- 16年毕业,建筑环境与设备工程专业,干的一直是工程想转IT专业,想从python入手请问咋开始学习
