我一直得到一个错误,说

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

我的代码太长了,不能在这里发布。什么样的场景会导致这个AttributeError, NoneType是什么意思,我该如何缩小范围?


当前回答

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

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

其他回答

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

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

其他人解释了什么是NoneType以及以它结束的常见方式(即,无法从函数返回值)。

另一个常见的原因是在你不期望的地方出现None,这是对可变对象进行就地操作的赋值。例如:

mylist = mylist.sort()

列表的sort()方法对列表进行就地排序,即修改mylist。但是该方法的实际返回值是None,而不是已排序的列表。你把None赋值给mylist。如果你下次尝试执行mylist.append(1), Python会给你这个错误。

“NoneType”为None值的类型。在本例中,变量生命周期的值为None。

实现这种情况的常见方法是调用一个缺少返回值的函数。

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

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

foo = None
foo.something = 1

or

foo = None
print(foo.something)

两者都会产生一个AttributeError: 'NoneType'