在 Objective-C 中你可以做 [variable valueForKeyPath:@"abc.def"]
或 [[variable abc] def]
如果 abc
doesn't exist on variable
你最终会得到一个 nil
值,并且不会得到错误或异常。这真的很方便。 Python中有这样的东西吗?我知道你可以做到(至少对于字典)
abc = variable.get('abc', None)
if abc:
def = abc.get('def', None)
或
try:
def = variable.get('abc').get('def')
except:
pass
这看起来非常冗长。当我只想访问对象的属性或取回 None 值时,有没有更简单的方法?
最佳答案
关于
def = variable.get('abc', {}).get('def',None)
好吧,这只适用于 dict..
关于python - 无需 try/catch 即可安全访问 Python 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11515620/