2

Using a similar approach to a previous question about subclassing a float class yields no keys in the dict. For example:

class Foo(dict):
    def __new__(cls, value, extra):
        return super().__new__(cls, value)

    def __init__(self, value, extra):
        dict.__init__(value)
        self.extra = extra

Running Foo({'a':1}, 1).keys() returns empty dict keys dict_keys([]).

How to correctly subclass a dict with extra arguments in Python?

Greg
  • 8,175
  • 16
  • 72
  • 125

1 Answers1

1

Change the line:

dict.__init__(value)

To:

dict.__init__(self, value)

Also consider composition instead of inheritance, because you're breaking away from the API of dict here (see LSP).

wim
  • 338,267
  • 99
  • 616
  • 750