在面向对象编程中,有时我们希望在超类中定义一些方法,这些方法在子类中有不同的实现。这通常通过多态性来实现,即在超类中定义一个方法,然后在各个子类中重写这个方法以提供特定的实现。
多态性:多态性是指允许一个接口或基类被用于多种子类对象,每个子类可以以自己的方式实现基类中的方法。
假设我们有一个超类 Animal
和两个子类 Dog
和 Cat
,我们希望在超类中定义一个 makeSound
方法,但每个子类有不同的实现。
from abc import ABC, abstractmethod
# 定义一个抽象基类
class Animal(ABC):
@abstractmethod
def makeSound(self):
pass
# 定义子类 Dog
class Dog(Animal):
def makeSound(self):
return "Woof!"
# 定义子类 Cat
class Cat(Animal):
def makeSound(self):
return "Meow!"
# 使用示例
def animal_sound(animal):
print(animal.makeSound())
dog = Dog()
cat = Cat()
animal_sound(dog) # 输出: Woof!
animal_sound(cat) # 输出: Meow!
问题:如果子类忘记重写超类的方法,会导致运行时错误。
解决方法:
ABC
和 @abstractmethod
装饰器强制子类实现方法。class Animal:
def makeSound(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def makeSound(self):
return "Woof!"
class Cat(Animal):
pass # 忘记重写方法
# 运行时会抛出异常
try:
cat_sound = Cat().makeSound()
except NotImplementedError as e:
print(e) # 输出: Subclass must implement abstract method
通过这种方式,可以在编译时或运行时确保子类正确实现了必要的方法,从而避免潜在的错误。
领取专属 10元无门槛券
手把手带您无忧上云