[英]Get value of class members with out AttributeError
See my example看我的例子
class MyClass1:
name = 'A'
class MyClass2:
foo = MyClass1()
obj1 = MyClass2()
Below code will result AttributeError
if obj1
or foo
is False
.如果obj1
或foo
为False
下面的代码将导致AttributeError
。
print obj1.foo.name
So I write following所以我写如下
if obj1:
if obj1.foo:
if obj1.foo.name:
print obj1.foo.name
What is the best way?什么是最好的方法? Can I avoid the repeating words in my code ?我可以避免代码中的重复单词吗?
You can use try/except
syntax to catch the exception.您可以使用try/except
语法来捕获异常。
try:
print obj1.foo.name
except AttributeError:
# do something
Your code could be simplified to two lines:您的代码可以简化为两行:
if obj1 and obj1.foo and obj1.foo.name:
print obj1.foo.name
It checks conditions one-by-one, and if any condition of all joined by and
is falsy the whole ... and ... and ...
condition becomes falsy and doesn't check inner conditions further.它逐一检查条件,如果所有由and
连接的条件为假,则整个... and ... and ...
条件变为假并且不会进一步检查内部条件。
The pythonic way to resolve this is by using try/execept
解决这个问题的try/execept
方法是使用try/execept
try:
name = obj1.foo.name
except AttributeError:
# raise error or pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.