0

EDIT: Oh, sorry guys. This question is a duplicate one, but not the dup of the linked one. I've found what i need in this question, maybe i should try more key word to search next time.Subclassing dict: should dict.init() be called?

In my case, I implement update, __setitem__ in the class StrKeyDict(dict), and __new__ inherited from dict may create a empty dict to ensure update can work, I don't think it's necessary to use super().__init__() again.

The code is from Fluent Python example-code/attic/dicts/strkeydict_dictsub.py

import collections.abc

class StrKeyDict(dict):

    def __init__(self, iterable=None, **kwds):
        super().__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        if isinstance(key, str):
            raise KeyError(key)
        return self[str(key)]

    def __contains__(self, key):
        return key in self.keys() or str(key) in self.keys()

    def __setitem__(self, key, item):
        super().__setitem__(str(key), item)

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def update(self, iterable=None, **kwds):
        if iterable is not None:
            if isinstance(iterable, collections.abc.Mapping):
                pairs = iterable.items()
            else:
                pairs = ((k, v) for k, v in iterable)
            for key, value in pairs:
                self[key] = value
        if kwds:
            self.update(kwds)

When we use

d = StrKeyDict(a=1,b=2) 

for example, to create instance d, the real happening is:

1.Call __new__ which inherited from the superclass dict to create a empty dict instance

2.Call __init__ to initialize the instance

Just like I said, I implement update, __setitem__ in the class StrKeyDict(dict). So is it necessary to use super().__init__() here. Thank you!

Community
  • 1
  • 1
Andy Guo
  • 127
  • 2
  • 7
  • `super().__init__()` does the same thing it does anywhere else, it calls `__init__()` on the super class. –  Mar 26 '16 at 17:53
  • becasue i implement `update`, `__setitem__` in the `class StrKeyDict(dict)`, and `__new__` inherited from `dict` may create a empty `dict` to ensure `update` can work, I don't think it's necessary to use `super().__init__()` again. – Andy Guo Mar 26 '16 at 18:05
  • if you know better than everyone else, why did you even ask this question? Especially if you are just going to argue with everyone, you do not want an answer, you want to be told you are correct, you aren't. –  Mar 26 '16 at 18:10
  • I didn't mean that. There is something wrong with the question and i edited again. "what's the meaning of `super().__init__()` "maybe misunderstood, so i change it to "is it necessary to use `super().__init__()` " in this case. By the way, I've run this code and it's okay, so i just wanna know is it "necessary" here. – Andy Guo Mar 26 '16 at 18:17
  • I don't see how this is a dupe of the linked question. That one is about what to pass to `super().__init()`, not about whether it should be called or not. – Stop harming Monica Mar 26 '16 at 18:22
  • @Goyo Thank you for this. By the way, i'm a non-English speaker, is there something not clear in my question to make others misunderstood? And do i really sound like arguing with other people? – Andy Guo Mar 26 '16 at 18:48
  • @AndyGuo I am not a native English speaker either but I think your question is clear enough and I don't see how the other one is related. You may ask another question as suggested and explain beforehand why you think your question is different from the linked one. – Stop harming Monica Mar 26 '16 at 18:59

2 Answers2

2

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class (dict). It typically creates its underlying data structure.

DevShark
  • 8,558
  • 9
  • 32
  • 56
  • i think what you said about "creates its underlying data structure" is the main purpose of `super().__init__()` in this case. – Andy Guo Mar 27 '16 at 04:23
2

The superclass' __init__() might or might not be doing something necessary to initialise it. If you know what's the case you can make an informed decision. If you don't know your best bet is to call it just in case.

Now if you don't call it because it is not necessary and the implementation of the base class changes in a way that make it necessary then you will have to fix it.

On the other hand there are a few cases where calling the superclass __init__() is a bad idea, for example if it does heavy calculations very specific to the superclass and that are different in the subclass.

FWIW my approach is always call super().__init__() unless I have a good reason not to call it.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56