类可以重写 __getattr__
方法来返回缺失属性的默认值:
class Example:
def __getattr__(self, attr):
return None
测试它:
>>> ex = Example()
>>> ex.attr = 1
>>> ex.attr
1
>>> ex.missing
>>>
然而,这种方式不能进行链式操作:
>>> ex.missing.missing
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'missing'
它也不能处理尝试调用不存在的方法:
>>> ex.impossible()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
为了解决这个问题,我们可以创建一个代理对象:
class GetAnything:
def __getattr__(self, attr):
return self
def __call__(self, *args, **kwargs):
return self
def __repr__(self):
return '<Missing value>'
GetAnything = GetAnything()
返回该值而不是None
:
class Example:
def __getattr__(self, attr):
return GetAnything
现在它可以按照需要进行链接:
>>> Example().missing_attribute.missing_method().whatever
<Missing value>