【发布时间】:2015-08-19 20:14:41
【问题描述】:
注意我不认为 abc 本质上解决了我正在寻找的问题。以另一种可能更好的方式重述,我正在寻找一种方法来部分实现 Parent.method,但也需要有一个 Subclass.method,它使用并添加到部分 Parent.method 实现。
我想部分定义一个抽象类方法,但仍然要求该方法也在子类中实现。例如:
class AbstractClass(object):
def amethod():
# some code that should always be executed here
vars = dosomething()
# But, since we're the "abstract" class
# force implementation through subclassing
if <somehow determine whether this has not been subclassed>:
raise NotImplementedError
class ActualClass(AbstractClass):
def amethod():
# Actual class code
code_here()
# And execute the super class code.
super(ActualClass, self).amethod()
【问题讨论】:
-
为什么你需要更多实际上什么都不做的类?
-
Abstract methods in Python 的可能重复项
-
@TigerhawkT3 这就是我想要做上述事情的原因。我确实希望它做一些事情,但是每个子类都应该发生一些事情。只是没有子类,部分是没有意义的。问这个问题的一部分是被告知“是的,这很糟糕,这样做你想做的事......”然而,到目前为止,这还没有发生。
-
这并不是说它不好(即产生错误或数据丢失),而是它可能是不必要的并且在很大程度上无法执行。如果有人出现并创建了一个子类,而该子类只不过是超类的包装器呢?
-
虽然我的特殊情况这不是问题,但这种方法肯定无法针对确定的执行。为此,我认为唯一真正的解决方案是通过 API 调用,其中 API 将强制执行额外的行为。虽然也可以使用一些元编程方法。
标签: python