简体   繁体   中英

Inconsistent Return Type

Class Human inherits from Python built-in 'dict' class. As an argument it expects a dictionary. .getCars() method returns a value stored in "car" or "cars" dictionary key. For the key "car" the return value is a string. For the key "cars" the value is a list of strings. So .getCars() method will be returning two types of values: string or list. Needless to say dealing with getCars() method will become tedious really fast. I would have to keep checking what it is returning this time: list or string... That would result to numerous if/else statements later on. My question : What design/approach to take in a situation like this? Should I enforce to the same type of return value (let's say regardless if there is only car or many - .getCars() always returns a list). While this approach would result to a consistent return value-type it may produce problems later. Since with a single car packed into a list variable I would have to do if returned_list: real_return_value=returned_list[0] which is kind of redundant too.

class Human(dict):
    def __init__(self, *args, **kwargs):
        super(Human, self).__init__(*args, **kwargs)
    def getCars(self):
        if 'cars' in self: return self.get('cars')
        elif 'car' in self: return self.get('car')

cars={'cars':['BMW','Porsche','Mercedes-Benz']}
car={'car':'Geo Metro'}

wealthy=Human(cars)
froogle=Human(car)

print wealthy.getCars()
print froogle.getCars()

I'd suggest normalizing the return type in addition to normalizing the key you use to look up the data. That is, always return a list of cars, even if there's only one under the key "car" . I don't think there is any more elegant solution:

def getCars(self):
    if "cars" in self:
        return self["cars"]
    elif "car" in self:
        return [self["car"]]  # build a list for the single car!
    else:
        return []  # return an empty list if neither key exists

An alternative to returning an empty list if no cars exist for a person might be to raise an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM