【发布时间】:2011-01-18 15:33:48
【问题描述】:
我有一个类层次结构:
class ParentClass:
def do_something(self):
pass # child classes have their own implementation of this
class ChildClass1(ParentClass):
def do_something(self):
<implementation here>
class ChildClass2(ParentClass):
def do_something(self, argument_x):
<implementation here>
class ChildClass3(ParentClass):
def do_something(self, argument_y):
<implementation here>
这里有两个问题:
- 方法 do_something() 在子类中有不同的接口:它在子类 2 和 3 中接受参数,但在子类 1 中没有参数
- do_something() 的参数有不同的名称,以强调它们在子类 2 和 3 中具有不同的含义。这将在下面通过使用示例变得更加清晰
这是如何使用这些类的:
有一个返回实例的工厂类:
class ChildFactory:
def get_child(self, argument):
if argument == '1':
return ChildClass1()
elif argument == '2':
return ChildClass2()
elif argument == '3':
return ChildClass3()
稍后在代码中:
...
# pseudocode, not python
child_type = ? # can have values '1', '2' or '3' at this moment
var1 = 1
var2 = 'xxx'
# var1 and var2 have different types, just to emphasize the difference in their
# meaning when being passed as arguments to do_something()
# this was mentioned above (the second problem)
child = ChildFactory.get_child(child_type)
if child is an instance of ChildClass1, child.do_something() is called
if child is an instance of ChildClass2, child.do_something(var1) is called
if child is an instance of ChildClass3, child.do_something(var2) is called
# end of pseudocode
问题:
- 上面提到的两个问题是不是设计不好?如果是,那么设计层次结构的正确方法是什么?
- 如何在python中统一编写伪代码sn-p?主要问题是避免在每个特定情况下使用巨大的 if/else 语句,因为它会使 ChildFactory.get_child() 中的 if/else 语句加倍
【问题讨论】: