python - 是否记录了通过实例访问类变量?

标签 python oop scope specifications

在 Python 中,可以通过该类实例访问类变量:

>>> class A(object):
...     x = 4
...
>>> a = A()
>>> a.x
4

很容易证明 a.x 确实解析为 A.x,而不是在构造期间复制到实例:

>>> A.x = 5
>>> a.x
5

尽管这种行为是 well known并且被广泛使用,我找不到任何关于它的权威文档。我能在 Python 文档中找到的最接近的是 section on classes :

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

[snip]

... By definition, all attributes of a class that are function objects define corresponding methods of its instances. So in our example, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. ...

但是,这部分专门讨论方法,因此它可能与一般情况无关。

我的问题是,这是否记录在案?我可以依赖这种行为吗?

最佳答案

引用 Python 中的 ClassesClass instances 部分 data model文档

A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although for new-style classes in particular there are a number of hooks which allow for other means of locating attributes).

...

A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes.

通常,这种用法很好,除了提到的特殊情况,如“特别是对于新式类,有许多 Hook 允许使用其他方法定位属性”。

关于python - 是否记录了通过实例访问类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313471/

相关文章:

javascript - 访问与实例变量同名的全局变量

Javascript函数变量作用域

python - 在列表中迭代字典

javascript - 为什么 getter 或 setter 在 JavaScript 中不能独立继承?

python - Elasticsearch - 不需要完全匹配

r - 为新类定义 S3 "Math"组泛型时出现意外的 log2 错误

ruby-on-rails - Ruby on Rails 和类变量混淆

angularjs - 从服务中刷新特定 Controller $scope

Python - 有效地将数据从元组列表提取到另一个列表

python - Emacs 协作缓冲区以错误的模式打开