繁体   English   中英

Python:预定义的类变量访问

[英]Python: Predefined class variable access

在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

那很正常 一个类的实例在该类的__dict__查找属性解析,以及所有祖先的__dict__ ,但是并非某个类的所有属性都来自其__dict__

特别是, Test__name__保留在表示类的C结构的字段中,而不是类的__dict__ ,并且该属性是通过type.__dict____name__ 描述符找到的。 Test实例不会在属性查找中使用它。

我对“为什么”没有很好的答案。 但是,使用__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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM