【发布时间】:2016-08-22 06:03:16
【问题描述】:
在一个框架中,我经常想提供一个基类,该基类是框架用户的子类。基类提供对基类的受控访问。实现此目的的一种方法是提供具有不同名称的未实现方法,例如通过添加下划线作为前缀:
class Base:
def method(self, arg):
# ...
result = self._method(arg)
# ...
return result
def _method(self, arg):
raise NotImplementedError
但是,此方案仅适用于一级继承。对于更多级别,不同的方法名称使得很难对正在发生的事情进行概览。此外,框架用户必须根据他选择的基类覆盖不同的方法:
class Base:
def method(self, arg):
# ...
result = self._method_sub(arg)
# ...
return result
def _method_sub(self, arg):
raise NotImplementedError
class Intermediate(Base):
def _method_sub(self, arg):
# ...
result = self._method_sub_sub(arg)
# ...
return result
def _method_sub_sub(self, arg):
raise NotImplementedError
当基方法需要访问子方法的返回值时,调用超方法无济于事。我觉得面向对象有点缺陷,缺少一个允许将调用转发到子类的child 关键字。有什么解决方案可以解决这个问题?
【问题讨论】:
-
@FujiApple 假设 Python 将具有最终方法。我将如何允许子类实现其中的一部分?我的示例中的方法并不是最终的。子类提供行为,基类包装它。基本方法可以向参数和返回值添加行为或范围检查。
-
我很难理解这个问题 - 我 认为 我可能知道你想要什么,但我真的不确定:有
Base.method()换行Base.methodSub()然后有Intermediate提供methodSub()实现。然后,父Base.method()可以对methodSub()的子实现进行任何前/后验证。如果这听起来不错,我可以举一个例子,如果不是,我会退出并让其他人弄清楚:) -
@FujiApple 没错。但是
Base和Intermediate都是框架提供的抽象类。对于框架用户扩展Intermediate,该类必须提供Intermediate.methodSubSub()等等。这不好,因为框架用户需要覆盖不同的方法,这取决于他选择的基类。 -
我根据我对您的问题的理解(可能仍有缺陷)在下面发布了一个答案,因为它太长了无法放入 cmets。如果我仍然错过了这一点,请告诉我,我会删除它。
标签: python python-3.x inheritance design-patterns frameworks