Python的多态

发布于:2024-07-08 ⋅ 阅读:(45) ⋅ 点赞:(0)

在 Python 中,多态(Polymorphism)是指不同的对象可以对相同的消息(方法调用)做出不同的响应。 简单来说,多态允许使用一个统一的接口来操作不同类型的对象,而这些对象会根据自身的类型来执行相应的具体操作。 例如,假设有一个父类 `Shape` 和几个子类 `Circle`、`Rectangle` 、`Triangle` ,它们都有一个 `area` 方法来计算面积。

class Shape:
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height

然后,可以创建这些不同形状的对象,并通过相同的方式调用 area 方法来获取它们各自的面积计算结果。

shapes = [Circle(5), Rectangle(4, 6), Triangle(3, 8)]

for shape in shapes:
    print(shape.area())

尽管都是调用 area 方法,但不同的子类对象会根据自己的实现计算并返回不同的结果,这就是多态的体现。它增加了代码的灵活性和可扩展性,使得程序更易于维护和扩展。 

多态性 示例:

#多态

#继承:多态一定是发生在子类和父类之间的重写:子类重写父类中的方法

class Animal:
    def say(self):
        print('animal')

class Cat(Animal):
    def say(self):
        print('I am a cat')

class Dog(Animal):
    def say(self):
        print('I am a dog')

class Duck(Animal):
    def say(self):
        print('I am a duck')

duck=Duck()
duck.say()

dog=Dog()
dog.say()

#输出分别为:
#I am a duck
#I am a dog

子类重写父类方法后同一个方法‘say’的输出不同,即呈现多态性。

在 Python 中,鸭子类型(Duck Typing)是一种编程风格。

其理念是:如果一个对象的行为(方法和属性)看起来像鸭子,走路像鸭子,叫声像鸭子,那么我们就可以把它当作鸭子。

换句话说,在使用对象时,不关注对象的类型,而是关注对象是否具有所需的方法和属性。只要对象具有所需的方法和属性,就可以在相应的上下文中使用,而不管它具体属于哪个类。

例如,如果有两个类 Bird 和 Plane ,它们都有一个 fly 方法。

class Bird:
    def fly(self):
        print("Bird is flying")

class Plane:
    def fly(self):
        print("Plane is flying")

def make_fly(obj):
    obj.fly()

在某个函数中,如果需要一个能够“飞行”的对象,我们可以接受这两个类的实例,因为它们都具有 fly 方法,符合“能够飞行”的要求。



bird = Bird()
# 创建了一个 `Bird` 类的实例 `bird`

plane = Plane()
# 创建了一个 `Plane` 类的实例 `plane`

make_fly(bird)
# 调用 `make_fly` 函数,并将 `bird` 作为参数传递进去
# 在函数内部,通过 `obj.fly()` 调用了 `Bird` 类中定义的 `fly` 方法,输出 "Bird is flying"

make_fly(plane)
# 调用 `make_fly` 函数,并将 `plane` 作为参数传递进去
# 在函数内部,通过 `obj.fly()` 调用了 `Plane` 类中定义的 `fly` 方法,输出 "Plane is flying"

 这种编程风格强调的是对象的行为,而不是对象的类型,使得代码更加灵活和可扩展。

鸭子类型示例:

#鸭子类型:长得像鸭子,它就是鸭子类型

#多个类中实现了同一个方法(当前的方法名一样)
class Cat:
      def say(self):
          print('I am a cat')

class Dog:
      def say(self):
          print('I am a dog')


class Duck:
      def say(self):
          print('I am a duck')

animal = Cat
animal().say()

animal = Dog
animal().say()

#输出:I am a cat
I am a dog

#这也是一种多态的体现


网站公告

今日签到

点亮在社区的每一天
去签到