我一直得到一个错误,说
AttributeError: 'NoneType' object has no attribute 'something'
我的代码太长了,不能在这里发布。什么样的场景会导致这个AttributeError, NoneType是什么意思,我该如何缩小范围?
我一直得到一个错误,说
AttributeError: 'NoneType' object has no attribute 'something'
我的代码太长了,不能在这里发布。什么样的场景会导致这个AttributeError, NoneType是什么意思,我该如何缩小范围?
当前回答
考虑下面的代码。
def return_something(someint):
if someint > 5:
return someint
y = return_something(2)
y.real()
这就会给出误差
AttributeError: 'NoneType'对象没有'real'属性
点如下所示。
在代码中,函数或类方法不返回任何东西或返回None 然后,您尝试访问该返回对象的属性(该属性为None),从而导致错误消息。
其他回答
NoneType意味着不是你认为你正在处理的任何类或对象的实例,你实际上得到的是None。这通常意味着上面的赋值或函数调用失败或返回意外结果。
它表示您试图访问的对象为None。None是python中的Null变量。 这种类型的错误发生在你的代码是这样的。
x1 = None
print(x1.something)
#or
x1 = None
x1.someother = "Hellow world"
#or
x1 = None
x1.some_func()
# you can avoid some of these error by adding this kind of check
if(x1 is not None):
... Do something here
else:
print("X1 variable is Null or None")
gdc是对的,但加上了一个非常常见的例子:
您可以以递归形式调用此函数。在这种情况下,您可能会以空指针或NoneType结束。在这种情况下,您可以得到这个错误。因此,在访问该参数的属性之前,检查它是否不是NoneType。
你有一个等于None的变量,你试图访问它的一个名为“something”的属性。
foo = None
foo.something = 1
or
foo = None
print(foo.something)
两者都会产生一个AttributeError: 'NoneType'
if val is not None:
print(val)
else:
# no need for else: really if it doesn't contain anything useful
pass
检查特定数据是否为空或空。