为什么reduce(getattr())有效,但reduce(hasattr())不起作用?

时间:2014-04-25 23:29:54

标签: python python-3.x

我可以使用functools.reduce()来使用getattr(),但我无法使用hasattr()。有人可以指出我做错了吗?

import functools

# Quick and dirty nested instances    
mt_class = type('mt_class', (object,), {})
this = mt_class()
setattr(this, 'that', mt_class())
setattr(this.that, 'the_other', mt_class())
setattr(this.that.the_other, 'my_str', "howdy!")


In [6]: functools.reduce(getattr, ['that', 'the_other'], this)
Out[6]: <__main__.mt_class at 0x88784cc>

In [7]: functools.reduce(getattr, ['that', 'the_other'], this).my_str 
Out[7]: 'howdy!'


In [8]: functools.reduce(hasattr, ['that', 'the_other'], this)
Out[8]: False


澄清: 是的,我希望reduce(hasattr())将返回True。

In [13]: hasattr(this.that.the_other, 'my_str')
Out[13]: True

1 个答案:

答案 0 :(得分:5)

result = reduce(getattr, ['attr_of_this', 'attr_of_attr_of_this'], this)相当于:

attr_of_this = getattr(this, 'attr_of_this')
result = getattr(attr_of_this, 'attr_of_attr_of_this')

reduce(hasattr, ['attr_of_this', 'attr_of_attr_of_this'], this)相当于:

true_or_false = hasattr(this, 'attr_of_this')
always_false_for_nonbool_attr = hasattr(true_of_false, 'attr_of_attr_of_this')

bool()没有attr_of_attr_of_this,因此结果为False