作者:关注了🐴
Github:Github
掘金:进去看看🐴
爱好: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.
....
....
....