Ton*_*ony 2 python idioms accessor
在Objective-C中,您可以执行[variable valueForKeyPath:@"abc.def"]或者[[variable abc] def]如果 abc不存在,variable您nil最终会获得一个值,并且不会出现错误或异常.这真的很方便.Python中有这样的东西吗?我知道你可以做(至少对于词典)
abc = variable.get('abc', None)
if abc:
def = abc.get('def', None)
Run Code Online (Sandbox Code Playgroud)
要么
try:
def = variable.get('abc').get('def')
except:
pass
Run Code Online (Sandbox Code Playgroud)
这似乎令人难以置信的冗长.当我只想访问对象的属性或获取None值时,有更简单的方法吗?
关于什么
def = variable.get('abc', {}).get('def',None)
Run Code Online (Sandbox Code Playgroud)
好吧,这只适用于dict ..