AttributeError: ‘dict‘ object has no attribute ‘has_key‘,多敲help()就能解决你还不知道?

作者关注了🐴

GithubGithub

掘金进去看看🐴

爱好Americano More Ice !

QQ学习交流群(new): 811792998

最近在搞常量定义池,使用了has_key()…话不多说

问题

if self.__dict__.has_key(name):
	rasie error

上面是报错代码

Traceback (most recent call last):
  File "D:...", line 24, in <module>
    r = CONST_POOL()
  File "D:...", line 20, in __init__
    self.URL = "..."
  File "D:...", line 15, in __setattr__
    if self.__dict__.has_key(name):
AttributeError: 'dict' object has no attribute 'has_key'

原因:作者使用的python版本是3.8.x的,此版本已经去除此方法

解决篇

话不多说,多种解决方法,爽起来~

# 报错版
if self.__dict__.has_key(name):
	raise error
# 普通版
if name in self.__dict__:
	raise error
# 高阶版
if self.__dict__.__contains__(name):
	raise error

Tips

python中的help()能更高效的解决哦~~

附上部分输出~~

Help on dict object:

__dict__ = class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if the dictionary has the specified key, else False.
 ....
 ....
 ....
结束语:如果遇到什么疑问或者建议的,可直接留言评论!作者看到会马上一一回复
如果觉得小白此文章不错或对你有所帮助,期待你的一键三连💫!❤️ ni ~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值