当我编写问题代码时,发生了以下错误:
AttributeError: 'NoneType' object has no attribute 'someMethod'
当我清楚地定义我的物体时。
我的代码看起来像这样:
#Assuming that someObject has method "someMethod"
otherList = []
for someObject in listOfObjects:
if someObject.someMethod() != True:
otherList.append(someObject)
答案 0 :(得分:0)
正如@Selcuk已经提到的,None
中有一个listOfObjects
。要捕获这种情况,您可以使用以下方法检查是否有此方法:
#Assuming that someObject has method "someMethod"
otherList = []
for someObject in listOfObjects:
if getattr(someObject, 'someMethod', lambda : True)() != True:
otherList.append(someObject)
getattr
将尝试获取该方法,如果它没有这样的方法,它将返回一个函数,如果被调用将返回True
。另一种方法就是捕获这些异常:
#Assuming that someObject has method "someMethod"
otherList = []
for someObject in listOfObjects:
try:
if someObject.someMethod() != True:
otherList.append(someObject)
except AttributeError():
# Catch the Error but just let it go, we wouldn't want to append it.
pass
顺便说一句,如果你知道,列表中的None
没有这样的问题,那么你的循环就有了一个不错的选择:
import itertools
import operator
otherList = list(itertools.filterfalse(operator.methodcaller('someMethod'), listOfObjects))
可能需要用ifilterfalse
替换filterfalse
和python2
即使它只保留返回False
的元素,而不是像你指定的!= True
,但我认为这是一个很好的选择,因为itertools和operator比正常迭代更快。