Python3笔记041 - 7.7 多态

第7章 面向对象程序设计

  • 7.1 面向对象概述
  • 7.2 类的定义
  • 7.3 类的实例化
  • 7.4 访问限制
  • 7.5 继承
  • 7.6 封装
  • 7.7 多态
  • 7.8 装饰器
  • 7.9 特殊方法

7.7 多态

多态(polymorphism),多个对象共用一个接口,形态表现不一样的现象称之为多态。

class Dog():

    def sound(self):
        print("汪汪")


class Cat():

    def sound(self):
        print("喵喵")


class Pig():

    def sound(self):
        print("哼哼")

# 这个函数接收一个animal参数,并调用它的sound方法
def sound_type(animal):
    animal.sound()


d = Dog()
c = Cat()
p = Pig()

sound(d)
sound(c)
sound(p)
output:
汪汪
喵喵
哼哼

狗、猫、猪都继承了动物类,并各自重写了kind方法。show_kind()函数接收一个animal参数,并调用它的kind方法。可以看出,无论我们给animal传递的是狗、猫还是猪,都能正确的调用相应的方法,打印对应的信息。这就是多态。

# 另一个多态实例
class Document():
    def __init__(self, name):
        self.name = name
    def show(self):
        raise NotImplementedError("Subclass must implement father class")


class Pdf(Document):
    def show(self):
        return "show pdf content"


class Word(Document):
    def show(self):
        return "show word content"


def show_document(doctype):

    if doctype == "pdf":
        pdf_obj = Pdf(doctype)
        print(pdf_obj.show())

    elif doctype == "word":
        word_obj = Word(doctype)
        print(word_obj.show())

show_document("pdf")

output:
show pdf content

猜你喜欢

转载自www.cnblogs.com/infuture/p/13352849.html
7.7