I'm trying to override dict
class in a way that is compatible with standard dict
class. How I can get access to parent dict
attribute if I override __getitem__
method?
class CSJSON(dict):
def __getitem__(self, Key : str):
Key = Key 'zzz' # sample of key modification for app use
return(super()[Key])
Then I receive error:
'super' object is not subscriptable.
If I use self[Key]
then I get infinite recursive call of __getitem__
.
CodePudding user response:
You have to explicitly invoke __getitem__
, syntax techniques like [Key]
don't work on super()
objects (because they don't implement __getitem__
at the class level, which is how []
is looked up when used as syntax):
class CSJSON(dict):
def __getitem__(self, Key : str):
Key = Key 'zzz' # sample of key modification for app use
return super().__getitem__(Key)
CodePudding user response:
Depending on your needs, working from collections.UserDict
or abc.MutableMapping
might be less painful than directly subclassing dict
. There are some good discussions here about the options: 1, 2, 3
How I can get access to parent dict attribute if I override getitem method?
More experienced users here seem to prefer MutableMapping, but UserDict provides a convenient solution to this part of your question by exposing a .data
dict
you can manipulate as a normal dict.