Python 中 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- 'NoneType' object has no attribute 'X' 错误

尝试访问或设置 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 值的属性时,例如 来自不返回任何内容的函数的赋值。 要解决该错误,请在访问属性之前更正分配。

  • 15
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迹忆客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值