How to “perfectly” override a dict?

后端 未结 5 2071
情话喂你
情话喂你 2020-11-22 08:14

How can I make as \"perfect\" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

It would seem

5条回答
  •  广开言路
    2020-11-22 08:56

    All you will have to do is

    class BatchCollection(dict):
        def __init__(self, *args, **kwargs):
            dict.__init__(*args, **kwargs)
    

    OR

    class BatchCollection(dict):
        def __init__(self, inpt={}):
            super(BatchCollection, self).__init__(inpt)
    

    A sample usage for my personal use

    ### EXAMPLE
    class BatchCollection(dict):
        def __init__(self, inpt={}):
            dict.__init__(*args, **kwargs)
    
        def __setitem__(self, key, item):
            if (isinstance(key, tuple) and len(key) == 2
                    and isinstance(item, collections.Iterable)):
                # self.__dict__[key] = item
                super(BatchCollection, self).__setitem__(key, item)
            else:
                raise Exception(
                    "Valid key should be a tuple (database_name, table_name) "
                    "and value should be iterable")
    

    Note: tested only in python3

提交回复
热议问题