Accessing class variables via instance

后端 未结 2 612
耶瑟儿~
耶瑟儿~ 2020-12-11 01:34

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

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


        
2条回答
  •  情书的邮戳
    2020-12-11 02:25

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

提交回复
热议问题