我主要关注 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()
}}
至少标准化您的函数输入的一个选项是让每种动物按其语言和栖息地进行分类并将其存储在字典中
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)