比嵌套更干净的替代方案 If/Else

Cleaner Alternative to Nested If/Else

我主要关注 create_animal 中 if/else 的替代方案。如果有更专业的方法来处理这个问题

在这种情况下,它是一个分类器,它基于确定动物是什么所需的可变数量的特征。由于人类是唯一会说英语的动物,所以 属性 就足够了。但是,如果他们改为咆哮,熊和狮子需要额外的 属性 栖息地才能弄清楚。我知道我可以更简洁地对这些条件进行分组,但这不是我要说明的内容。

class Human:
    self.family = 'Hominidae'
    self.order = 'Primate'

class Bear:
    self.family = 'Ursidae'
    self.order = 'Carnivora'

class Lion:
    self.family = 'Felidae'
    self.order = 'Carnivora'
    
def create_animal(language, roars, habitat):
    if language == 'English':
        return Human()
    elif roars == True:
        if habitat == 'forest':
            return Bear()
        elif habitat == 'savannah':
            return Lion()

animal1 = create_animal(None, roars=True,habitat='forest') # Will be a bear
animal2 = create_animal(language = 'English', roars=False,habitat='town') # Will be a human
animal3 = create_animal(language = None, roars=True,habitat='savannah') # Will be a lion

这可行,但对于现实世界的一些复杂性,我不喜欢嵌套的 if/else 变得多么令人讨厌,我认为必须有一个很好的方法来使用分类图来做到这一点,例如这个,但我不确定如何处理它。

species_classification_map = {
    'speaks_english':Human(),
    'roars':{
        'forest':Bear(),
        'savannah':Lion()
    }}

你可以定义一个矩阵为一个pandas.DataFrame对象,它的列是你的动物特征,包括你的动物的名字,每一行是动物种类的记录。然后,当您需要创建具有某些特征的新动物时,您可以轻松找到具有正值的列。

这是否满足您的要求?

至少可以标准化您的函数输入的一个选项是让每只动物按其语言和栖息地分类并将其存储在字典中

class Human():
    def __init__(self):
        self.family = 'Hominidae'
        self.order = 'Primate'

class Bear():
    def __init__(self):
        self.family = 'Ursidae'
        self.order = 'Carnivora'

class Lion():
    def __init__(self):
        self.family = 'Felidae'
        self.order = 'Carnivora'
    
def create_animal(language, habitat):
    #dict of language, habitat
    animals={('english','civilization'):Human(),
            ('roars','forest'):Bear(),
            ('roars','savannah'):Lion()}
    #human habitat could also be None for simplicity
    return animals[(language,habitat)]

b=create_animal('roars','forest')
b
<__main__.Bear at 0x210c8795460>

some_dude=create_animal('english','civilization')
some_dude
<__main__.Human at 0x210c87953a0>