为什么我会收到 AttributeError: 'NoneType'对象没有属性“某物”?

发布于 2024-12-27 22:19:34 字数 602 浏览 1 评论 0原文

我收到一条错误消息,内容为

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

我如何理解此消息?

哪些一般情况可能会导致此类 AttributeError,以及如何识别问题?


这是AttributeError的特例。它值得单独处理,因为有很多方法可以从代码中获取意外的 None 值,因此这通常是一个不同的问题;对于其他 AttributeError,问题可能很容易出在属性名称上。

另请参阅什么是 None 值?什么是“NoneType”对象? 了解 None< /code> 及其类型,NoneType

I am getting an error message that says

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

How can I understand this message?

What general scenarios might cause such an AttributeError, and how can I identify the problem?


This is a special case of AttributeErrors. It merits separate treatment because there are a lot of ways to get an unexpected None value from the code, so it's typically a different problem; for other AttributeErrors, the problem might just as easily be the attribute name.

See also What is a None value? and What is a 'NoneType' object? for an understanding of None and its type, NoneType.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

笑,眼淚并存 2025-01-03 22:19:34

NoneType 意味着您实际上拥有的是 None,而不是您认为正在使用的任何类或对象的实例。这通常意味着上面的赋值或函数调用失败或返回意外结果。

NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.

丢了幸福的猪 2025-01-03 22:19:34

您有一个等于 None 的变量,并且您正在尝试访问它的一个名为“something”的属性。

foo = None
foo.something = 1

或者

foo = None
print(foo.something)

两者都会产生 AttributeError: 'NoneType'

You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'.

foo = None
foo.something = 1

or

foo = None
print(foo.something)

Both will yield an AttributeError: 'NoneType'

西瑶 2025-01-03 22:19:34

NoneType 是值None 的类型。在本例中,变量lifetime 的值为None

发生这种情况的常见方法是调用缺少返回的函数。

但是,还有无数其他方法可以将变量设置为 None。

The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.

怀里藏娇 2025-01-03 22:19:34

考虑下面的代码。

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

这会给你错误

AttributeError:“NoneType”对象没有属性“real”

所以要点如下。

  1. 在代码中,函数或类方法不返回任何内容或返回 None
  2. 然后您尝试访问该返回对象的属性(即 None),从而导致错误消息。

Consider the code below.

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

This is going to give you the error

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

So points are as below.

  1. In the code, a function or class method is not returning anything or returning the None
  2. Then you try to access an attribute of that returned object(which is None), causing the error message.
时光病人 2025-01-03 22:19:34
if val is not None:
    print(val)
else:
    # no need for else: really if it doesn't contain anything useful
    pass

检查特定数据是否不为空或为空。

if val is not None:
    print(val)
else:
    # no need for else: really if it doesn't contain anything useful
    pass

Check whether particular data is not empty or null.

若水般的淡然安静女子 2025-01-03 22:19:34

它表示您尝试访问的对象NoneNone 是 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")

It means the object you are trying to access None. None is a Null variable in python.
This type of error is occure de to your code is something like this.

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")
寒冷纷飞旳雪 2025-01-03 22:19:34

获取 None 的另一个常见原因是错误地将方法的返回值分配给所操作的对象。

numbers = [2, 3, 4, 0, 42, 17]
numbers = numbers.sort()  # error!
numbers.append(10000000)

这里的问题是 .sort 方法就地修改了列表,并返回 None。您需要

numbers.sort()

或者

numbers = numbers.sorted()

(在这种情况下,前者可能是首选。)

还有其他几种具有类似签名的方法。 sort 是一种常见的方法,但这只是其中的一个示例。


此信息有一个中等高度赞成的答案,但其作者删除了它。我添加了一个新答案,以使讨论保持合理完整。

Another common cause of getting None is to incorrectly assign a method's return value to the manipulated object.

numbers = [2, 3, 4, 0, 42, 17]
numbers = numbers.sort()  # error!
numbers.append(10000000)

The problem here is that the .sort method modifies the list in place, and returns None. You want either

numbers.sort()

or

numbers = numbers.sorted()

(The former should probably be preferred in this scenario.)

There are several other methods with a similar signature. sort is a common one, but it's just one example of this.


There was a moderately highly upvoted answer with this information, but its author deleted it. I'm adding a new answer to keep the discussion reasonably complete.

千里故人稀 2025-01-03 22:19:34

在构建估计器(sklearn)时,如果您忘记在 fit 函数中返回 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 添加到 fit 函数可修复该错误。

When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.

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' object has no attribute 'transform'?

Adding return self to the fit function fixes the error.

旧情勿念 2025-01-03 22:19:34

该错误意味着您正在尝试访问 None 的属性或方法,但 NoneType 没有任何属性或方法。当您调用不返回任何内容的函数时,可能会发生这种情况,导致其返回值为 None。示例:

>>> exec("'FOO'").lower()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'lower'

发生这种情况是因为内置函数 exec 没有返回值,而我们尝试在 None 上调用 lower 方法。

The error means that you are trying to access an attribute or method of None, but NoneType does not have any. This can happen when you call a function that does not return anything, which results in its return value is None. Example:

>>> exec("'FOO'").lower()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'lower'

This happens because the built-in function exec does not return a value, and we are trying to call the lower method on None.

夜血缘 2025-01-03 22:19:34

gddc 是对的,但添加一个非常常见的示例:

您可以以递归形式调用此函数。在这种情况下,您可能会得到空指针或 NoneType。在这种情况下,您可能会收到此错误。因此,在访问该参数的属性之前,请检查它是否不是 NoneType

g.d.d.c. is right, but adding a very frequent example:

You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it's not NoneType.

像极了他 2025-01-03 22:19:34

这里的其他答案都没有给我正确的解决方案。我遇到了这种情况:

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')

None of the other answers here gave me the correct solution. I had this scenario:

def my_method():
   if condition == 'whatever':
      ....
      return 'something'
   else:
      return None

answer = my_method()

if answer == None:
   print('Empty')
else:
   print('Not empty')

Which errored with:

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'

In this case you can't test equality to None with ==. To fix it I changed it to use is instead:

if answer is None:
   print('Empty')
else:
   print('Not empty')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文