在线上有几个例子,其中if...else
语句被使用多态性/继承的结构替换。This link显示了一些类似于我想要实现的东西。我有一个嵌套结构,如下所示:
def wishthiswouldbeobjectoriented(figuretype, randomtype):
if figuretype=='list':
# do some stuff and return a list
out = 'figure type is list'
elif figuretype=='random':
if randomtype=='all':
out = 'figure type is random and randomtype is all'
elif randomtype=='selection':
out = 'figure type is random and randomtype is selection'
return out
if __name__ == '__main__':
figuretype = 'random'
randomtype = 'selection'
print(wishthiswouldbeobjectoriented(figuretype, randomtype))
我猜应该有一种方法可以使用多态性/继承将其转换为面向对象的代码。有没有人能在python
中提供一个简短的例子来演示如何将上面的代码转换成面向对象的代码?你知道吗
下面的内容纯粹是机械地使用继承作为分派方法,而不是一系列显式的
if
语句。这些选项不是作为参数传递给函数,而是隐式编码在类本身中。你知道吗添加以下内容:
扩展以下内容:
相关问题 更多 >
编程相关推荐