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, sinceMyClass.f
is a function, butx.i
is not, sinceMyClass.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?
Not only can you rely on this behavior, you constantly do.
Think about methods. A method is merely a function that has been made a class attribute. You then look it up on the instance.
In the case of objects like functions, this isn't a plain lookup, but some magic occurs to pass
self
automatically. You may have used other objects that are meant to be stored as class attributes and looked up on the instance; properties are an example (check out theproperty
builtin if you're not familiar with it.)As okm notes, the way this works is described in the data model reference (including information about and links to more information about the magic that makes methods and properties work). The Data Model page is by far the most useful part of the Language Reference; it also includes among other things documentation about almost all the
__foo__
methods and names.Refs the
Classes
andClass instances
parts in http://docs.python.org/reference/datamodel.htmlGenerally, 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".