我可以重载{}操作符来创建字典吗? [英] Can I overload the {} operators for creating dictionaries?

查看:121
本文介绍了我可以重载{}操作符来创建字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作dict类的派生变体,以便可以通过属性访问语法来访问字典值(因此,而不是使用字典['foo'] ,您可以执行字典.foo 。)这是我迄今为止所做的:

  class dict(dict):
__getattr__ = dict .__ getitem__

但是,我的代码片段给出了问题:

  eventD = {'rrule_end':无} 
。 。 。
。 。 。
#(一段时间后)
打印event.rrule_end

这是因为字典创建的{}运算符没有被重载。是否可以使dictName = {}语法创建我的派生类而不是普通字典的实例?

解决方案

否。您不能覆盖dict literal语法。 (您也不能覆盖列表文字语法或字符串文字语法,或数字文字语法或任何文字语法。)



您必须创建您的类明确。给你的班级一个名字像MyDict,然后做

  eventD = MyDict({'rrule_end':None})


I am making a derived variant of the dict class such that a dictionary value can be accessed through attribute access syntax (so instead of doing dictionary['foo'] you could do dictionary.foo.) This is what I have so far:

class dict(dict): 
    __getattr__ = dict.__getitem__

However, this snippet of my code gives it problems:

eventD = {'rrule_end':None}
. . .
. . .
#(some time later)
print event.rrule_end

This is because the { } operators for dictionary creation have not been overloaded. Is it possible to make the dictName = { } syntax create an instance of my derived class instead of an ordinary dictionary?

解决方案

No. You cannot override dict literal syntax. (You also can't override list literal syntax, or string literal syntax, or number literal syntax, or any literal syntax.)

You have to create the instance of your class explicitly. Give your class a name like MyDict and then do

eventD = MyDict({'rrule_end':None})

这篇关于我可以重载{}操作符来创建字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆