python - Is it necessary to use super().__init__() in this case? -


edit: oh, sorry guys. question duplicate one, not dup of linked one. i've found need in question, maybe should try more key word search next time.subclassing dict: should dict.init() called?

in case, implement update, __setitem__ in class strkeydict(dict), , __new__ inherited dict may create empty dict ensure update can work, don't think it's necessary use super().__init__() again.

the code 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 not none:             if isinstance(iterable, collections.abc.mapping):                 pairs = iterable.items()             else:                 pairs = ((k, v) k, v in iterable)             key, value in pairs:                 self[key] = value         if kwds:             self.update(kwds) 

when use

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

for example, create instance d, real happening is:

1.call __new__ inherited superclass dict create empty dict instance

2.call __init__ initialize instance

just said, implement update, __setitem__ in class strkeydict(dict). necessary use super().__init__() here. thank you!

the superclass' __init__() might or might not doing necessary initialise it. if know what's case can make informed decision. if don't know best bet call in case.

now if don't call because not necessary , implementation of base class changes in way make necessary have fix it.

on other hand there few cases calling superclass __init__() bad idea, example if heavy calculations specific superclass , different in subclass.

fwiw approach call super().__init__() unless have reason not call it.


Comments