通过instan访问类变量

2024-03-28 23:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我的问题是,这有记录吗?我能相信这种行为吗?


Tags: of实例文档objectisonexamplemyclass
2条回答

你不仅可以依靠这种行为,你还经常这样做。

想想方法。一个方法仅仅是一个已经成为类属性的函数。然后在实例中查找它。

>>> def foo(self, x):
...     print "foo:", self, x
... 
>>> class C(object):
...     method = foo # What a weird way to write this! But perhaps illustrative?
... 
>>> C().method("hello")
foo: <__main__.C object at 0xadad50> hello

对于像函数这样的对象,这不是一个简单的查找,但是会发生一些魔术来自动传递self。您可能已经使用了其他要存储为类属性并在实例上查找的对象;属性是一个示例(如果您不熟悉property内置函数,请查看它)

正如okm所指出的,这种工作方式在data model reference中进行了描述(包括有关使方法和属性工作的魔法的更多信息的信息和链接)。到目前为止,数据模型页是语言引用中最有用的部分;它还包括关于几乎所有__foo__方法和名称的文档。

引用http://docs.python.org/reference/datamodel.html中的ClassesClass instances部分

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.

一般来说,这种用法很好,除了“特别是新样式的类,有许多钩子允许其他方式定位属性”这样的特殊情况。

相关问题 更多 >