简体   繁体   English

如何为内置字典类的子类定义默认字典键

[英]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.

相关问题 覆盖内置类,尤其是字典类 - Override built-in classes, in particular, dictionary class 如何从嵌套字典创建包含子字典键的列表? - How to create a List containing a sub dictionary keys , from nested dictionary? 如何将PyQt5 QtWidgets.QTabWidget()正确添加到子类化QWidget - How to add PyQt5 QtWidgets.QTabWidget() properly to sub-classed QWidget 从字典键、子键和值的列表构造字典 - Construct a dictionary from a list of dictionary keys, sub-keys and values 从字典中分配和调用内置函数 (Python) - Assigning and Calling built-in functions from a dictionary (Python) 如何将dict对象的内置方法值转换为字典 - How to convert built-in method values of dict object to dictionary 如何不加区别地仅使用python内置功能(来自两个列表)来创建字典? - How can I create a dictionary without distinction and only using python built-in funtions(from two lists)? 是否有内置Python可以从字典或对象中进行不可知的选择? - Is there a Python built-in that can select agnostically from either a dictionary or an object? 初始化从具有特定字典的类构建的对象 - Initialize an object built from a class with a specific dictionary 字典理解可生成内置类型的值 - Dictionary Comprehension to generate values of built-in type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM