Skip to main content
 首页 » 编程设计

python之打印在 __getattr__ 中不起作用

2025年05月04日14birdshome

我有这门课:

class Meta: 
    def __getattr__(self, atr): 
        print('get', atr) 
    def __setattr__(self, atr, atr_value): 
        print('{0} with value {1} added'.format(atr, atr_value)) 
        self.__dict__[atr] = atr_value 

当我设置一个属性时 - print 有效:

>>> x.a = 1 
a with value 1 added 

但是当我调用它时:

>>> x.a 
1 

返回的值没有print 输出。

非常感谢您的帮助。

请您参考如下方法:

__getattr__ 仅在属性不存在时调用。您想覆盖 __gettattribute__。

def __getattribute__(self, name): 
    print("get", name) 
    return object.__getattribute__(self, name)