Skip to main content
 首页 » 编程设计

python之内置操作的新样式类属性搜索

2024年11月01日11虾米哥

<分区>

考虑以下经典类和新样式类之间的区别。

   class A(): 
        data = 'abcd' 
        def __getattr__(self, name):  
            return getattr(self.data, name) 
 
    class B(object): 
        data = 'abcd' 
        def __getattr__(self, name):  
            return getattr(self.data, name) 
 
 
 
    print(A()[0])       # Prints 'a' 
    print(B()[0])       # TypeError: 'B' object does not support indexing 

我知道对此属性的解释是新样式对象属性搜索从类而不是内置操作的实例开始。 但是类对象也定义了 __getattr__ 以及为什么它没有为此处缺少的属性 __getitem__ 调用。