为什么我会得到 AttributeError: 'NoneType' object has no attribute 'something'?

问题描述 投票:0回答:10

我收到一条错误消息说

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

我如何理解这条信息?

什么一般情况可能会导致这样的

AttributeError
,我该如何识别问题?


这是

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

另见什么是无值?什么是“NoneType”对象?了解

None
及其类型,
NoneType

python attributeerror nonetype
10个回答
426
投票

NoneType 意味着您实际上得到了

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


136
投票

你有一个等于 None 的变量,你正试图访问它的一个名为“某物”的属性。

foo = None
foo.something = 1

foo = None
print(foo.something)

两者都会产生一个

AttributeError: 'NoneType'


17
投票

NoneType
是值
None
的类型。在这种情况下,变量
lifetime
的值为
None
.

发生这种情况的一种常见方法是调用缺少

return
的函数。

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


15
投票

考虑下面的代码。

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

y = return_something(2)
y.real()

这会给你错误

AttributeError: 'NoneType' 对象没有属性 'real'

所以要点如下。

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

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

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


4
投票

表示您要访问的对象

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

3
投票

构建估算器 (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
添加到拟合函数中修复错误。


1
投票

g.d.d.c.是对的,但添加一个非常常见的例子:

您可以以递归形式调用此函数。在那种情况下,您可能会以空指针或

NoneType
结束。在这种情况下,您可能会收到此错误。因此,在访问该参数的属性之前,请检查它是否不是
NoneType
.


0
投票

如果在 Flask 应用程序中注释掉 HTML,就会出现此错误。这里 qual.date_expiry 的值为 None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

删除行或修复它:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

-1
投票

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

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')
© www.soinside.com 2019 - 2024. All rights reserved.