Python 中 AttributeError: ‘NoneType‘ object has no attribute ‘X‘ 错误

文章目录

    • AttributeError: ‘NoneType’ object has no attribute ‘X’ 介绍
    • AttributeError: ‘NoneType’ object has no attribute ‘X’ 常见原因
    • AttributeError: ‘NoneType’ object has no attribute ‘X’ 错误解决方法
    • 总结

AttributeError: ‘NoneType’ object has no attribute ‘X’ 介绍

Python “AttributeError: ‘NoneType’ object has no attribute” 发生在我们尝试访问 None 值的属性时,例如 来自不返回任何内容的函数的赋值。 要解决该错误,请在访问属性之前更正分配。

这是一个非常简单的示例,说明错误是如何发生的。

example = None

# ⛔️ AttributeError: 'NoneType' object has no attribute 'append'
example.append('hello')

Python 中 AttributeError-

尝试访问或设置 None 值的属性会导致错误。

如果打印正在访问其属性的变量,它将为 None,因此您必须追踪变量被分配 None 值的位置并更正分配。

None 值(显式赋值除外)的最常见来源是不返回任何内容的函数。

# 👇️ this function returns None
def do_math(a, b):
    print(a * b)


# 👇️ None
example = do_math(10, 10)

# ⛔️ AttributeError: 'NoneType' object has no attribute 'my_attribute'
print(example.my_attribute)


# ✅ use this if you need to check if a variable is not None
# before accessing an attribute
if example is not None:
    print('variable is not None')
else:
    print('variable is None')

请注意 ,我们的 do_math 函数没有显式返回值,因此它隐式返回 None。

我们将调用函数的结果分配给一个变量,并试图访问导致错误的属性。

AttributeError: ‘NoneType’ object has no attribute ‘X’ 常见原因

“AttributeError: ‘NoneType’ object has no attribute” 的发生有多种原因:

  1. 具有不返回任何内容的函数(隐式返回 None)。
  2. 将变量显式设置为 None
  3. 将变量分配给调用不返回任何内容的内置函数的结果。
  4. 具有仅在满足特定条件时才返回值的函数。

一些内置方法(例如排序)会就地改变数据结构并且不返回值。 换句话说,它们隐式返回 None。

my_list = ['c', 'b', 'a']

my_sorted_list = my_list.sort()

print(my_sorted_list)  # 👉️ None

# ⛔️ AttributeError: 'NoneType' object has no attribute 'pop'
my_sorted_list.pop()

sort() 方法对列表进行就地排序并且不返回任何内容,因此当我们将调用该方法的结果分配给变量时,我们为该变量分配了一个 None 值。

避免使用会改变原始对象的方法进行赋值,因为它们中的大多数不返回值并隐式返回 None

如果一个变量有时存储一个真实值,有时存储 None,则可以在访问属性之前明确检查该变量是否不是 None

example = None

if example is not None:
    print('variable is not None')
else:
    print('variable is None')  # 👉️ this runs

仅当示例变量未存储 None 值时,if 块才会运行,否则运行 else 块。

错误的另一个常见原因是具有仅在满足条件时才返回值的函数。

def get_num(a):
    if a > 100:
        return a


result = get_num(5)

print(result)  # 👉️ None

get_num 函数中的 if 语句仅在传入的参数大于 100 时运行。

在所有其他情况下,该函数不返回任何内容并最终隐式返回 None

AttributeError: ‘NoneType’ object has no attribute ‘X’ 错误解决方法

要解决这种情况下的错误,我们要么必须检查函数是否未返回 None,要么在不满足条件时返回默认值。

def get_num(a):
    if a > 100:
        return a
    return 0 # 👈️ returns 0 if condition not met


result = get_num(5)

print(result)  # 👉️ 0

现在,无论条件是否满足,函数都保证返回一个值。

总结

Python “AttributeError: ‘NoneType’ object has no attribute” 发生在我们尝试访问 None 值的属性时,例如 来自不返回任何内容的函数的赋值。 要解决该错误,请在访问属性之前更正分配。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年6月16日
下一篇 2023年6月16日

相关推荐