class MyClass:
    def __init__(self, x):
        self.x = x
    def __getattribute__(self, name):
        # 当访问属性时,这个方法会被调用
        print(f"Accessing the attribute: {name}")
        try:
            # 使用 super() 来避免无限递归
            return super().__getattribute__(name)
        except AttributeError:
            # 如果属性不存在,可以自定义处理逻辑
            print(f"{name} not found.")
            return None
# 示例使用
obj = MyClass(10)
print(obj.x)  # 输出: Accessing the attribute: x
              #       10
print(obj.y)  # 输出: Accessing the attribute: y
              #       y not found.
              #       None__getattribute__ 是一个特殊方法,它会在每次访问类的任何属性时被调用。__getattribute__ 方法,使得每次访问属性时都会打印一条消息。super().__getattribute__(name) 来获取属性的实际值,避免了无限递归的问题(因为直接调用 self.name 会再次触发 __getattribute__)。AttributeError 并返回自定义的默认值或处理逻辑。上一篇:python clip
下一篇:python webui
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站