类块中定义的名称范围不扩展到方法块.这是为什么? [英] The scope of names defined in class block doesn't extend to the methods' blocks. Why is that?

查看:28
本文介绍了类块中定义的名称范围不扩展到方法块.这是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

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

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

<预><代码>>>>A类():我 = 1def f(自我):打印(一)>>>a = A()>>>a.i1>>>a.f()回溯(最近一次调用最后一次):文件<pyshell#7>",第 1 行,在 <module> 中a.f()文件<pyshell#4>",第 4 行,在 f 中打印(一)NameError: 全局名称 'i' 未定义

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

<预><代码>>>>a = A()>>>A类():我 = 1def f(自我):打印(A.i)>>>a = A()>>>a.f()1

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

解决方案

这似乎与使用显式 self 参数有关,以及要求所有方法调用和实例属性都显式访问使用 self.如果将类作用域函数作为普通函数访问的罕见情况比通过 self 作为方法访问它的常见情况要容易得多,那至少会很奇怪.类变量通常也通过 Python 中的实例访问.

相比之下,在 C++ 中,类作用域在所有方法中都是可见的,但是调用一个方法会隐式传递this.这似乎是另一个明智的选择.

Reading the documentation I came across the following paragraph:

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope.

I decided to try accessing class variable from a method myself:

>>> 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

I know that the variable i may be accessed by explicitly pointing to the class name A.i:

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

The question is why the developers of the language made class variables not visible from methods? What is the rationale behind it?

解决方案

This seems to be related to the use of an explicit self parameter, and the requirement that all method calls and instance attribute accesses explicitly use self. It would be at least strange if the uncommon case of accessing a class scope function as a normal function would be much easier than the common case of accessing it as a method via self. Class variables are usually also accessed via the instance in Python.

In C++, in contrast, the class scope is visibile in all methods, but calling a method implicitly passes this. This seems to be the other sane choice.

这篇关于类块中定义的名称范围不扩展到方法块.这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆