我一直得到一个错误,说
AttributeError: 'NoneType' object has no attribute 'something'
我的代码太长了,不能在这里发布。什么样的场景会导致这个AttributeError, NoneType是什么意思,我该如何缩小范围?
我一直得到一个错误,说
AttributeError: 'NoneType' object has no attribute 'something'
我的代码太长了,不能在这里发布。什么样的场景会导致这个AttributeError, NoneType是什么意思,我该如何缩小范围?
当前回答
这里没有一个答案是正确的。我有这样一个场景:
def my_method():
if condition == 'whatever':
....
return 'something'
else:
return None
answer = my_method()
if answer == None:
print('Empty')
else:
print('Not empty')
错误如下:
File "/usr/local/lib/python3.9/site-packages/gitlab/base.py", line 105, in __eq__
if self.get_id() and other.get_id():
AttributeError: 'NoneType' object has no attribute 'get_id'
在这种情况下,你不能用==测试是否等于None。为了修复它,我把它改为使用:
if answer is None:
print('Empty')
else:
print('Not empty')
其他回答
其他人解释了什么是NoneType以及以它结束的常见方式(即,无法从函数返回值)。
另一个常见的原因是在你不期望的地方出现None,这是对可变对象进行就地操作的赋值。例如:
mylist = mylist.sort()
列表的sort()方法对列表进行就地排序,即修改mylist。但是该方法的实际返回值是None,而不是已排序的列表。你把None赋值给mylist。如果你下次尝试执行mylist.append(1), Python会给你这个错误。
gdc是对的,但加上了一个非常常见的例子:
您可以以递归形式调用此函数。在这种情况下,您可能会以空指针或NoneType结束。在这种情况下,您可以得到这个错误。因此,在访问该参数的属性之前,检查它是否不是NoneType。
if val is not None:
print(val)
else:
# no need for else: really if it doesn't contain anything useful
pass
检查特定数据是否为空或空。
“NoneType”为None值的类型。在本例中,变量生命周期的值为None。
实现这种情况的常见方法是调用一个缺少返回值的函数。
然而,还有无数种其他方法可以将变量设置为None。
你有一个等于None的变量,你试图访问它的一个名为“something”的属性。
foo = None
foo.something = 1
or
foo = None
print(foo.something)
两者都会产生一个AttributeError: 'NoneType'