Python:预定义的类变量访问

时间:2017-03-09 00:49:09

标签: python

在Python中,我能够从类和实例中访问非预定义的类变量。但是,我无法从对象实例访问预定义的类变量(例如" name ")。我错过了什么?感谢。

这是我写的测试程序。

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

2 个答案:

答案 0 :(得分:2)

这是正常的。类的实例在属性解析的类__dict__中查找,以及所有祖先的__dict__,但并非所有类的属性都来自其__dict__

特别是,Test的{​​{1}}保存在表示类的C结构中的字段中,而不是在类的__name__中,并且通过{找到属性{1}} __dict__中{1}} descriptor__name__的实例不会查看此属性查找。

答案 1 :(得分:0)

我对“为什么”没有很好的答案。但是这里是你如何使用__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'
>>>