如何在不破坏默认行为的情况下覆盖 getattr ?
要覆盖__getattr__Python 中的方法,同时保留未明确定义的属性的默认行为,可以遵循以下模式:
__getattr__
__dict__
super()
以下示例演示了如何执行此操作:
class MyClass: def __init__(self): self.existing_attr = "I exist!" def __getattr__(self, name): # Custom behavior for missing attributes if name == 'dynamic_attr': return "I am a dynamically created attribute!" # For any other missing attribute, use the default behavior # You can raise an AttributeError or return a default value raise AttributeError(f"{name} is not a valid attribute") # Example usage obj = MyClass() # Accessing an existing attribute print(obj.existing_attr) # Output: I exist! # Accessing a dynamically created attribute print(obj.dynamic_attr) # Output: I am a dynamically created attribute! # Attempting to access an undefined attribute try: print(obj.undefined_attr) except AttributeError as e: print(e) # Output: undefined_attr is not a valid attribute
existing_attr
dynamic_attr
undefined_attr
AttributeError