[英]Python: Predefined class variable access
In Python, I am able to access the non-predefined class variables both from the class as well as instances. 在Python中,我可以从类以及实例中访问未预定义的类变量。 However, I am not able to access the predefined class variables (such as " name ") from the object instances. 但是,我无法从对象实例访问预定义的类变量(例如“ name ”)。 What am I missing? 我想念什么? Thanks. 谢谢。
Here is a test program that I wrote. 这是我编写的测试程序。
class Test:
'''
This is a test class to understand why we can't access predefined class variables
like __name__, __module__ etc from an instance of the class while still able
to access the non-predefined class variables from instances
'''
PI_VALUE = 3.14 #This is a non-predefined class variable
# the constructor of the class
def __init__(self, arg1):
self.value = arg1
def print_value(self):
print self.value
an_object = Test("Hello")
an_object.print_value()
print Test.PI_VALUE # print the class variable PI_VALUE from an instance of the class
print an_object.PI_VALUE # print the class variable PI_VALUE from the class
print Test.__name__ # print pre-defined class variable __name__ from the class
print an_object.__name__ #print the pre-defined class varible __name__ from an instance of the class
That's normal. 那很正常 Instances of a class look in that class's __dict__
for attribute resolution, as well as the __dict__
s of all ancestors, but not all attributes of a class come from its __dict__
. 一个类的实例在该类的__dict__
查找属性解析,以及所有祖先的__dict__
,但是并非某个类的所有属性都来自其__dict__
。
In particular, Test
's __name__
is held in a field in the C struct representing the class, rather than in the class's __dict__
, and the attribute is found through a __name__
descriptor in type.__dict__
. 特别是, Test
的__name__
保留在表示类的C结构的字段中,而不是类的__dict__
,并且该属性是通过type.__dict__
的__name__
描述符找到的。 Instances of Test
don't look at this for attribute lookup. Test
实例不会在属性查找中使用它。
I don't have a great answer for "why". 我对“为什么”没有很好的答案。 But here's how you can get to them, using __class__: 但是,使用__class__可以找到它们:
>>> class Foo(object): pass
...
>>> foo = Foo()
>>> foo.__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__name__'
>>> foo.__class__.__name__
'Foo'
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.