根据自变量来检验不同的子类
问题描述:
我有一个RoundRobinChecker
和PlayoffChecker
类,它们都从ViolationChecker
继承,它检查给定的循环法或淘汰赛匹配是否通过规则。根据自变量来检验不同的子类
构造函数有一个参数,匹配项:ViolationChecker(match)
。现在,如果比赛是季后赛(match.playoff
),则应该实例化PlayoffChecker
,否则应该是RoundRobinChecker
。我可以这样做:
checkers = [PlayoffChecker(match) if match.playoff else RoundRobinChecker(match) for match in matches]
但是,这是一种不干净的做法。是否可以调用父类的构造函数ViolationChecker(match)
,这会创建相应子类的实例?
我可以在这里用什么设计以透明的方式选择适当的类?
答
为了使ViolationChecker(match)
的工作,我们可以覆盖在你的父类的__new__
method这样的:
class ViolationChecker:
def __new__(cls, match):
if match.playoff:
cls= PlayoffChecker
else:
cls= RoundRobinChecker
inst= object.__new__(cls)
return inst #implicit call to inst.__init__(match)
然而,这不是很明显的人谁读取您的代码ViolationChecker(match)
返回一个子类的实例。我建议增加一个明确名称的静态方法来ViolationChecker
,这样的事情:
class ViolationChecker:
@staticmethod
def new_for_match(match):
if match.playoff:
cls= PlayoffChecker
else:
cls= RoundRobinChecker
inst= cls(match)
return inst
现在你可以做ViolationChecker.new_for_match(match)
,这体现了该match
实例创建一个专门ViolationChecker
更明确的意向。