简体   繁体   English

返回类型不一致

[英]Inconsistent Return Type

Class Human inherits from Python built-in 'dict' class. Human类继承自Python内置的“ dict”类。 As an argument it expects a dictionary. 作为参数,它需要字典。 .getCars() method returns a value stored in "car" or "cars" dictionary key. .getCars()方法返回存储在“ car”或“ cars”字典键中的值。 For the key "car" the return value is a string. 对于键“ car”,返回值是一个字符串。 For the key "cars" the value is a list of strings. 对于键“ cars”,该值是字符串列表。 So .getCars() method will be returning two types of values: string or list. 因此.getCars()方法将返回两种类型的值:字符串或列表。 Needless to say dealing with getCars() method will become tedious really fast. 不用说处理getCars()方法将很快变得很乏味。 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. 我将不得不继续检查它这次返回的是什么:列表或字符串...稍后将导致大量的if / else语句。 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). 我应该强制使用相同类型的返回值.getCars()不管是否只有car或很多车.getCars()总是返回列表)。 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. 因为只有一辆车装在列表变量中,所以if returned_list: real_return_value=returned_list[0] ,我就必须这样做,这也是多余的。

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" . 也就是说,即使键"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. 如果一个人不存在汽车,则返回空列表的另一种方法可能是引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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