如果我有node.child1.child2
,我可以有效地使用h asattr(node, 'child1.child2')
吗?如果没有child1
或只是返回false,它会出错吗?
答案 0 :(得分:6)
hasattr
不会使用这样的虚线名称并向下导航属性链。但你可以写一个函数来做到这一点:
def get_deep_attr(obj, attrs):
for attr in attrs.split("."):
obj = getattr(obj, attr)
return obj
def has_deep_attr(obj, attrs):
try:
get_deep_attr(obj, attrs)
return True
except AttributeError:
return False
答案 1 :(得分:3)
这是一种方法:
def hasattrdeep(obj, *names):
for name in names:
if not hasattr(obj, name):
return False
obj = getattr(obj, name)
return True
这样称呼:
hasattrdeep(node) is True # A side-effect. Could be made invalid if really desired by raising TypeError if len(names) == 0
hasattrdeep(node, 'foo') is False
hasattrdeep(node, 'child1') is True
hasattrdeep(node, 'child1', 'foo') is False
hasattrdeep(node, 'child1', 'child2') is True