提问人:Jacob Griffin 提问时间:1/21/2012 最后编辑:Karl KnechtelJacob Griffin 更新时间:3/27/2023 访问量:1821725
为什么我会收到 AttributeError: 'NoneType' object has no attribute 'something'?
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
问:
我收到一条错误消息,内容如下:
AttributeError: 'NoneType' object has no attribute 'something'
我该如何理解此消息?
哪些一般情况可能导致这样的情况,我该如何识别问题?AttributeError
这是 AttributeError
s 的特例。它值得单独处理,因为有很多方法可以从代码中获取意外的 None
值,因此这通常是一个不同的问题;对于其他 AttributeError
s,问题可能同样容易出在属性名称上。
另请参阅什么是 None 值?和什么是“NoneType”对象?,以了解 None
及其类型 NoneType
。
答:
NoneType 意味着,您实际上拥有的不是您认为正在使用的任何类或对象的实例,而是 .这通常意味着上面的赋值或函数调用失败或返回意外结果。None
评论
您有一个等于 None 的变量,并且您正在尝试访问该变量的一个名为“something”的属性。
foo = None
foo.something = 1
或
foo = None
print(foo.something)
两者都将产生一个AttributeError: 'NoneType'
评论
None
foo = None
foo = something()
something()
None
是值的类型。在本例中,变量的值为 。NoneType
None
lifetime
None
发生这种情况的一种常见方法是调用缺少 .return
但是,有无数种其他方法可以将变量设置为 None。
评论
lifetime
None
None
请考虑下面的代码。
def return_something(someint):
if someint > 5:
return someint
y = return_something(2)
y.real()
这将给你带来错误
AttributeError:“NoneType”对象没有属性“real”
所以要点如下。
- 在代码中,函数或类方法不返回任何内容或返回 None
- 然后,您尝试访问返回对象的属性(即 None),从而导致错误消息。
G.D.D.C. 是对的,但添加一个非常常见的例子:
您可以以递归形式调用此函数。在这种情况下,最终可能会出现 null 指针或 。在这种情况下,您可能会收到此错误。因此,在访问该参数的属性之前,请检查它是否不是 .NoneType
NoneType
评论
if foo is not None:
return
它表示您尝试访问的对象。 是 Python 中的一个变量。
这种类型的错误是 de 你的代码是这样的。None
None
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")
您可能会在 Flask 应用程序中注释掉 HTML 时出现此错误。此处 qual.date_expiry 的值为 None:
<!-- <td>{{ qual.date_expiry.date() }}</td> -->
删除该行或修复它:
<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>
在构建估计器 (sklearn) 时,如果忘记在拟合函数中返回 self,则会出现相同的错误。
class ImputeLags(BaseEstimator, TransformerMixin):
def __init__(self, columns):
self.columns = columns
def fit(self, x, y=None):
""" do something """
def transfrom(self, x):
return x
AttributeError:“NoneType”对象没有属性“transform”?
添加到拟合函数可修复错误。return self
评论
return
return None
if something: return value
return None
something
if val is not None:
print(val)
else:
# no need for else: really if it doesn't contain anything useful
pass
检查特定数据是否为空或 null。
评论
else: pass
完全没用;如果你没有任何东西要放进去,只需省略它。else:
这里的其他答案都没有给我正确的解决方案。我遇到过这种情况:
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
==
is
if answer is None:
print('Empty')
else:
print('Not empty')
评论
return None
评论
AttributeError