我有一个方法foo()
,它最终返回一个名为john的Student
。
#!/usr/bin/python3
from random import randint
class Student(object):
name = ""
def foo():
if randint(0,1) == 0:
student = Student()
student.name = 'john'
else:
student = None
return student
我想获取 foo()
返回的学生姓名(避免 NPE 并避免多次调用 foo()
)。
我的实际解决方案是:
student = foo()
print(student.name if student is not None else None)
是否可以在一行中完成此操作,而不创建临时变量?
最佳答案
您可以使用getattr(obj, 'attr_to_get', default_value)
。
在您的示例中,解决方案是 getattr(foo(), 'name', None)
。
关于python:获取对象arg并在一行中检查NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309938/