Can hasattr go multiple children deep in Python?
If I have node.child1.child2
, can I use hasattr(node, 'child1.child2')
effectiv开发者_如何学编程ely? Will it error if there's no child1
or simply return false?
hasattr
doesn't take a dotted name like that and navigate down attribute chains. But you can write a function to do it:
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
Here's one way of doing it:
def hasattrdeep(obj, *names):
for name in names:
if not hasattr(obj, name):
return False
obj = getattr(obj, name)
return True
Call it like this:
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
精彩评论