首页 > 解决方案 > How do I make a subclass of "dict" that returns a fallback value when it can't find a value for a key?

问题描述

I want to create SafeDict, a subclass of dict.

When asked to retrieve a value for a non existing key, SafeDict should return a fallback value.
(I know there are other ways to do this, but I'm practicing my OOP skills.)

Right now I have:

class SafeDict(dict):
    def __getitem__(self, key):
        try:
            super().__getitem__(key)
        except KeyError:
            return "Beetle"

a = {"Ford": "Mustang"}
b = SafeDict({"Ferrari": "Enzo"})

print(a["Ford"])  # This prints "Mustang" (good)
#print(a["Aston"]) # This raises KeyError (good)

print(b["Ferrari"]) # This should print "Enzo", but it prints "None" (bad)
print(b["Aston"])  # This prints "Beetle" (good)

Maybe print(b["Ferrari"]) prints None beacuse super() runs the __getitem__ method on the list superclass, and that class has no dictionary with "Ferrari": "Enzo" in it?

I tried to remove the super(), and use self, but I ran into recursion problems.

Help?

标签: pythonpython-3.xlistclassoop

解决方案


You forgot to return the super() value:

class SafeDict(dict):
    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except KeyError:
            return "Beetle"

When a method has no explicit return statement, the function implicitly returns None


推荐阅读