我可以重载{}操作符来创建字典吗? [英] Can I overload the {} operators for creating dictionaries?
问题描述
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屋!