相关疑难解决方法(0)

类块中定义的名称范围不会扩展到方法的块.这是为什么?

阅读文档我遇到了以下段落:

范围定义块内名称的可见性.如果在块中定义了局部变量,则其范围包括该块.如果定义发生在功能块中,则作用域将扩展到定义块中包含的任何块,除非包含的块为名称引入了不同的绑定.类块中定义的名称范围仅限于类块; 它没有扩展到方法的代码块 - 这包括了解和生成器表达式,因为它们是使用函数作用域实现的.

我决定尝试自己从方法中访问类变量:

>>> class A():
    i = 1
    def f(self):
        print(i)            

>>> a = A()

>>> a.i
1

>>> a.f()
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a.f()
  File "<pyshell#4>", line 4, in f
    print(i)
NameError: global name 'i' is not defined
Run Code Online (Sandbox Code Playgroud)

我知道i可以通过显式指向类名来访问该变量A.i:

>>> a = A()
>>> class A():
    i = 1
    def f(self):
        print(A.i)          
>>> a = A()
>>> a.f()
1
Run Code Online (Sandbox Code Playgroud)

问题是为什么该语言的开发人员使方法中的类变量不可见?它背后的理由是什么?

python oop scope class

10
推荐指数
2
解决办法
1926
查看次数

标签 统计

class ×1

oop ×1

python ×1

scope ×1