Skip to main content
 首页 » 编程设计

python之检查对象是否有属性,不依赖 '__getattr__'

2024年11月01日9zlslch

有没有一种方法可以检查对象是否具有不依赖于 __getattr__ 或对象实现细节的属性?

考虑下面的代码。我希望 Proxy 将它无法处理的事情委托(delegate)给 Wrapped。代码有效,但我想避免测试 attr in self.__dict__ (我更喜欢稳定的接口(interface)来执行此操作,而不使用实现怪癖)。函数 hasattr 在这里没有帮助,因为它通过 __getattr__ 路由到包装对象。

class Wrapped: 
    def __init__(self): 
        self.a = 0 
        self.b = 1 
 
class Proxy: 
    def __init__(self, wrapped): 
        object.__setattr__(self, 'wrapped', wrapped) 
        object.__setattr__(self, 'a', 2) 
    def __getattr__(self, attr): 
        return getattr(self.wrapped, attr) 
    def __setattr__(self, attr, value): 
        if attr in self.__dict__:  # <-- Don't like this, hasattr doesn't work 
            object.__setattr__(self, attr, value) 
        elif hasattr(self.wrapped, attr): 
            setattr(self.wrapped, attr, value) 
        else: object.__setattr__(self, attr, value) 

试驾:

>>> w = Wrapped() 
>>> p = Proxy(w) 
>>> p.a 
2 
>>> p.b 
1 
>>> p.a = 3 
>>> p.a 
3 
>>> w.a 
0 
>>> p.b = 4 
>>> p.b 
4 
>>> w.b 
4 
>>> p.c = 5 
>>> p.c 
5 
>>> w.c 
AttributeError: 'Wrapped' object has no attribute 'c' 

请您参考如下方法:

内置hasattr()功能

is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.

inspect模块有 getattr_static()方法,可用于

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__()".

使用此方法,您可以定义一个类似于 hasattr() 的 hasattr_static() 方法,但调用 inspect.getattr_static(object, name) 而不是 getattr(object, name):

import inspect 
 
 
def hasattr_static(object, name): 
    try: 
        inspect.getattr_static(object, name) 
        return True 
    except AttributeError: 
        return False 

然后在 Proxy 类的 __setattr__() 方法中使用它作为检查:

def __setattr__(self, attr, value): 
    if hasattr_static(self, attr): 
        object.__setattr__(self, attr, value) 
    elif hasattr(self.wrapped, attr): 
        setattr(self.wrapped, attr, value) 
    else: 
        object.__setattr__(self, attr, value) 

或者,您可以使用 dir()函数而不是 __dict__ 来检索对象的属性列表,或者使用 inspect.getmembers() .