可以使用多态来实现将不同类实例的不同独立操作放到一个类中。多态是指同一个方法名可以根据不同的对象调用不同的实现。下面是一个示例代码:

class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Woof!")

class Cat(Animal):
    def sound(self):
        print("Meow!")

class Cow(Animal):
    def sound(self):
        print("Moo!")

class AnimalSound:
    def make_sound(self, animal):
        animal.sound()

dog = Dog()
cat = Cat()
cow = Cow()

animal_sound = AnimalSound()
animal_sound.make_sound(dog)  # 输出: Woof!
animal_sound.make_sound(cat)  # 输出: Meow!
animal_sound.make_sound(cow)  # 输出: Moo!

在上面的示例中,定义了一个Animal基类和几个子类DogCatCow,它们都实现了sound方法。然后定义了一个AnimalSound类,其中的make_sound方法接收一个Animal对象作为参数,并调用其sound方法。通过调用make_sound方法,可以将不同类实例的不同独立操作放到一个类中。

python 把不同类实例的不同独立操作放到一个类中

原文地址: http://www.cveoy.top/t/topic/iZSB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录