[英]How to define default dictionary keys for sub-classed from built-in dictionary class
SubClass()
is a sub-class of built-in Python dictionary: SubClass()
是内置Python字典的子类:
class SubClass(dict):
def __init__(self, *args, **kwargs):
super(SubClass, self).__init__(*args, **kwargs)
Now with any dictionary variable I can declare an instance of SubClass
. 现在,使用任何字典变量,我都可以声明SubClass
的实例。 Each dictionary key will become a key of SubClassed instance automatically (which is pretty cool): 每个字典键将自动成为SubClassed实例的键(非常酷):
myDictionary={'city':'New York', 'year':2014}
instance=SubClass(myDictionary)
print instance['city']
print instance.keys(), instance.values(), instance.items()
I would like to define a set of default dictionary keys so each SubClass
object (instance) gets them on declaration. 我想定义一组默认的字典键,以便每个SubClass
对象(实例)在声明时获取它们。 I could: 我可以:
class SubClass(dict):
def __init__(self, *args, **kwargs):
super(SubClass, self).__init__(*args, **kwargs)
self['id']=None
self['number']=None
self['oneMoreDefaultKey']=None
But that takes a lot of typing and looks ugly. 但这需要大量输入并且看起来很丑。 I rather would like to achieve the same with a minimum amount of code. 我宁愿用最少的代码来达到相同的目的。
I don't think that defaultdict
is what you want, since that gives you the same value for any missing key, rather than just the ones you specify. 我不认为defaultdict
是你想要的,因为这给了你同样的价值任何丢失的钥匙,而不仅仅是你指定的人。 You're only talking about 3 lines of code either way, so it's tough to imagine it getting too much simpler. 您只是在谈论两种方式的三行代码,因此很难想象它变得太简单了。 However, you can achieve what you're looking for a little bit more concisely like this: 但是,您可以像下面这样更加简洁地实现所需的功能:
class SubClass(dict):
DEFAULT_KEYS = ['id', 'number', 'oneMoreDefaultKey']
def __init__(self, *args, **kwargs):
super(SubClass, self).__init__(*args, **kwargs)
self.update({key: None for key in self.DEFAULT_KEYS})
If you want certain, specific keys to have default values, you'll need to list those keys somewhere. 如果您希望特定的特定键具有默认值,则需要在某些地方列出这些键。 Calling self.update()
does what your code does: 调用self.update()
执行您的代码:
class SubClass(dict):
def __init__(self, *args, **kwargs):
super(SubClass, self).__init__(*args, **kwargs)
self.update({
'id':None,
'number':None,
'oneMoreDefaultKey':None})
instance = SubClass({'city':'New York', 'year':2014})
print instance['id'], instance['year']
If you want all keys to have default values, and all of the default values are the same, then you are better off using collections.defaultdict
: 如果您希望所有键都具有默认值,并且所有默认值都相同,那么最好使用collections.defaultdict
:
import collections
instance = collections.defaultdict(lambda : None, {'city':'New York', 'year':2014})
print instance['id'], instance['year']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.