为什么Dict生成实例时,key只能是变量?dict的key不是可以为字符串、数字、变量吗?
Topic sourcea=Dict(‘214’=1,b=2)
# 上面你写的这句问题很大
# 首先你创建字典实例对象传关键字参数时的key是变量不要加引号,比如
a = Dict(x=1, y=2)
# 相当于:
d = {'x':1, 'y':2}
a = Dict(**d)
# 而不是写成:
a = Dict{'x'=1,'y'=2}
# 你那样写是给字符串214赋值真离谱
# 而且你214上面的引号还是中文的
# 建议重新看看前面的基础
- 1
haildceu1
class Dict(dict):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
a=Dict(‘214’=1,b=2)
print(a)
运行结果:SyntaxError: expression cannot contain assignment, perhaps you meant "=="?