通过实例访问类变量 [英] Accessing class variables via instance

查看:49
本文介绍了通过实例访问类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>A类(对象):... x = 4...>>>a = A()>>>斧头4

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

<预><代码>>>>A.x = 5>>>斧头5

尽管这种行为众所周知并被广泛使用,但我找不到任何关于它的权威文档.我能在 Python 文档中找到的最接近的是 关于类的部分:

<块引用>

class MyClass:《》《一个简单的示例类》《》我 = 12345def f(自我):返回你好世界"

[剪辑]

... 根据定义,作为函数对象的类的所有属性都定义了其实例的相应方法.所以在我们的例子中,xf 是一个有效的方法引用,因为 MyClass.f 是一个函数,但 xi 不是,因为 MyClass.i 不是....

然而,这部分专门讨论方法,所以它可能与一般情况无关.

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

解决方案

引用 http://docs.python.org/reference/datamodel.html

<块引用>

一个类有一个由字典对象实现的命名空间.班级属性引用被翻译成本字典中的查找,例如,C.x 被转换为 C.__dict__["x"](尽管对于新式类,特别是有许多钩子允许其他方式定位属性)

类实例是通过调用类对象创建的(见上文).一个类实例有一个作为字典实现的命名空间,它是搜索属性引用的第一个位置.当一个在那里找不到属性,并且实例的类有一个按该名称的属性,搜索将继续使用该类属性.

通常,这种用法很好,除了作为特别是新式类,有许多钩子允许其他定位属性的方法"提到的特殊情况.

In Python, class variables can be accessed via that class instance:

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

It's easy to show that a.x is really resolved to A.x, not copied to an instance during construction:

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

Despite the fact that this behavior is well known and widely used, I couldn't find any definitive documentation covering it. The closest I could find in Python docs was the 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. ...

However, this part talks specifically about methods so it's probably not relevant to the general case.

My question is, is this documented? Can I rely on this behavior?

解决方案

Refs the Classes and Class instances parts in http://docs.python.org/reference/datamodel.html

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.

Generally, this usage is fine, except the special cases mentioned as "new-style classes in particular there are a number of hooks which allow for other means of locating attributes".

这篇关于通过实例访问类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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