如何创建可以实例化的父类,但其所有方法必须在子类中实现?

时间:2020-08-07 23:30:40

标签: python python-3.x python-2.7 overriding python-2.x

我想强制子类实现或重写父类中的所有方法,但我希望能够从中实例化父类。因此,我需要父类具有适当的实现,而不是简单地引发NotImplementedError异常。

如果子类没有覆盖其父类的所有方法,我希望Python编译器对我大喊。

例如:

class Parent:

  def __init__(self, name):
    self.name = name

  def greetMorning(self):
    print("Good morning")

  def greetEvening(self):
    print("Good evening")
  
  def greetNight(self):
    print("Goodnight")

class Child(Parent):
  # This __init__() doesn't matter, I can change it to whatever
  def __init__(self):
    pass
  
  # The compiler should complain about a missing implementation for greetMorning()

  def greetEvening(self):
    print("Konbanwa")
  
  def greetNight(self):
    print("Oyasumi")

# If Parent() was abstract, I would not be able to create an instance, but I need to create one.
naruto = Parent("Uzumaki Naruto")
naruto.greetMorning()
naruto.greetEvening()
naruto.greetNight()

boruto = Child()
boruto.greetMorning()
boruto.greetEvening()
boruto.greetNight()

我更喜欢针对Python 2的方法,因为这是我在工作中使用的方法,但是我很高兴能够阅读Python 3的任何方法,因为这是我在家中使用的方法。

0 个答案:

没有答案