【问题标题】:Use abstract method after inheriting继承后使用抽象方法
【发布时间】:2017-01-24 09:59:37
【问题描述】:

使用 PyCharm IDE。 我想将 2 个抽象类 A+B 继承到 1 个新类 C 中。我想实现一个类的方法并使用另一个类的方法,该方法在稍后的类 E 中实现,使用 A 在 D 中的实现。

我的问题是:在创建C类时,intelliJ要我实现所有方法,所以A类的方法和B类的方法。我只想实现 A 类方法,但需要 B 类的“接口”来知道哪些方法可供我使用。有没有办法告诉 intelliJ 我不想在新类中实现某些类的抽象方法?

甚至 - 有没有办法以更好的方式完成所有这些工作?

class A(metaclass=ABCMeta):
    """interface class"""  
    @abstractmethod
    def click(self, c): pass

class B(metaclass=ABCMeta):
    """interface class"""   
    @abstractmethod
    def do_something(self): pass

class C(A, B):
    # implement methods of B here, use abstract methods of A 
    # as interface to know what methods are available for use
    def do_something(self):
        self.click("anything")

class D(A):
    # implement A
    def click(self, c):
        print("I clicked {}".format(c))

class E(C,D):
    # merge implementations to create runnable `do_something()`
    def main():
        self.do_something()

E.main()

【问题讨论】:

  • 您可以简单地禁止检查:# noinspection PyAbstractClass

标签: python inheritance intellij-idea pycharm multiple-inheritance


【解决方案1】:

正如所写,您的类 C 仍然是抽象的,因为它没有实现来自 A 的抽象方法 - 所以应该这样标记:

class C(A, B, metaclass=ABCMeta):
    # implement methods of B here, use abstract methods of A 
    # as interface to know what methods are available for use
    def do_something(self):
        self.click("anything")

【讨论】:

  • 我已经考虑过了,但是当 C 被声明为 ABCMeta 时,有没有办法强制 B 的所有抽象方法在 C 中实现?
  • 不(至少不是直接)-但是当您掌握代码时为什么需要这个?无论如何:您确定多重继承是正确的解决方案吗?也许组合+委托会更有意义?
  • 我想将代码提供给其他人贡献并需要他们拥有A的接口但实现B的所有方法。也是的,我将重新考虑多重继承的解决方案并尝试另一种方法。感谢您的意见
猜你喜欢
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 2012-08-06
  • 2014-07-09
  • 2017-11-07
  • 1970-01-01
  • 2019-04-28
相关资源
最近更新 更多