AttributeError: 'NoneType' object has no attribute 'add'

孤街醉人 提交于 2019-12-11 21:59:44

问题


I got the following error

AttributeError: 'NoneType' object has no attribute 'add'

while I tried this.

not_yet_bought_set = set()
.
.
.
for value in set_dict.itervalues():
    for item in value:
        not_yet_bought_set = not_yet_bought_set.add(item)

I dont't get why I got this error, is it because I always make not_yet_bought_set new? I make this, because when I only do

not_yet_bought_set.add(item)

there wont be all the items from all values. I do not know why.

value are sets and

not_yet_bought_set.union(value)

also generate this error

Thanks for any help.


回答1:


not_yet_bought_set.add(item)

this will return None and you are assigning it to not_yet_bought_set. So, not_yet_bought_set becomes None now. The next time

not_yet_bought_set = not_yet_bought_set.add(item)

is executed, add will be invoked on None. Thats why it fails.

To fix this, simply do this. Dont assign this to anything.

 not_yet_bought_set.add(item)



回答2:


set.add returns nothing.

>>> s = set()
>>> the_return_value_of_the_add = s.add(1)
>>> the_return_value_of_the_add is None
True

Replace following line:

not_yet_bought_set = not_yet_bought_set.add(item)

with:

not_yet_bought_set.add(item)


来源:https://stackoverflow.com/questions/19853872/attributeerror-nonetype-object-has-no-attribute-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!