内置的hasattr() https://docs.python.org/3/library/functions.html#hasattr功能
是通过调用实现的getattr(object, name)
看看它是否会引发AttributeError
or not.
The inspect https://docs.python.org/3/library/inspect.html模块有getattr_static() https://docs.python.org/3/library/inspect.html#inspect.getattr_static方法,可用于
通过描述符协议检索属性而不触发动态查找,__getattr__()
or __getattribute__()
".
使用此方法,您可以定义一个hasattr_static()
方法类似于hasattr()
,但是调用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
然后在__setattr__()
你的方法Proxy
类作为检查:
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() https://docs.python.org/3.5/library/functions.html#dir函数而不是__dict__
检索对象的属性列表,或使用inspect.getmembers() https://docs.python.org/3/library/inspect.html#inspect.getmembers.