Discuss / Python / 为什么Dict生成实例时,key只能是变量?dict的key不是可以为字符串、数字、变量吗?

为什么Dict生成实例时,key只能是变量?dict的key不是可以为字符串、数字、变量吗?

Topic source

haildceu1

#1 Created at ... [Delete] [Delete and Lock User]

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 "=="?

凡响skyline

#2 Created at ... [Delete] [Delete and Lock User]
a=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

Reply