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


  • 1

Reply