Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

python - Accessing class variables via instance

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...