Polymorphism in Python is the ability of an object to take on many forms. It is a concept that allows us to use a single interface to represent different types of objects. Here is a code sample that demonstrates polymorphism in Python:

# Parent class
class Animal:

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

    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

# Child classes
class Dog(Animal):

    def speak(self):
        return self.name + " barks"

class Cat(Animal):

    def speak(self):
        return self.name + " meows"

class Cow(Animal):

    def speak(self):
        return self.name + " moos"

# Instantiate objects
dog = Dog("Buddy")
cat = Cat("Whiskers")
cow = Cow("Bessie")

# Call speak method on each object
print(dog.speak())
print(cat.speak())
print(cow.speak())

In this code sample, we have a parent class called Animal and three child classes called Dog, Cat, and Cow. Each child class has its own implementation of the speak method, which returns a string that represents the sound the animal makes.

We then instantiate objects from each of the child classes and call the speak method on each object. Because each object is of a different class, calling the speak method on each object returns a different string. This demonstrates the concept of polymorphism, where a single interface (the speak method) can be used to represent different types of objects (the Dog, Cat, and Cow objects).

polymorphism python coding sample

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

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