class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 使用面向对象编程
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
from abc import ABC, abstractmethod
class Animal(ABC):
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# 使用面向接口的编程
dog = Dog()
cat = Cat()
print(dog.speak()) # 输出: Woof!
print(cat.speak()) # 输出: Meow!
原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/90233.html