将对象附加到列表;执行功能是给出属性错误

时间:2016-03-19 03:43:48

标签: python python-2.7

当我编写问题代码时,发生了以下错误: 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)

1 个答案:

答案 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比正常迭代更快。