-1

Came across code where a class which extends Dict class and overrides the methods.

Following code snippet is what I can't understand:

class HeaderKeyDict(dict):
"""
A dict that title-cases all keys on the way in, so as to be
case-insensitive.
"""
    # More methods

    def __getitem__(self, key):
        return dict.get(self, key.title())

    def get(self, key, default=None):
        return dict.get(self, key.title(), default)

   # More methods

What is confusing me is what is dict.get(self, ...) doing ? Is this similar to dict.get(key) method ?

Will dict.get(self) call the self.get() method when we do [ ] on this class object ?

mittal
  • 915
  • 10
  • 29

1 Answers1

1

In this case dict.get(self, key.title()) is equivalent to super().get(key.title()). It is calling the "original" .get method of the dict class but forcing the key to be "titlized".

To understand why dict.get(self, key.title()) is equivalent to super().get(key.title()) let's have a look at a simpler class:

class Foo:
    def bar(self):
        print('bar')

Now, calling Foo().bar() is the same as calling Foo.bar(Foo()). This is essentially the same as what is going on in your case without the inheritance.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Thanks. Right after I posted this question, found a similar Q/A for list https://stackoverflow.com/questions/4093029/how-to-inherit-and-extend-a-list-object-in-python – mittal Aug 10 '17 at 12:12
  • I had never seen such a invocation before `dict.get(self)`, and that is what got me confused – mittal Aug 10 '17 at 12:18