zoukankan      html  css  js  c++  java
  • python面向对象之多态

    实现多态的步骤:

    1、定义一个父类(Base),实现某个方法(比如:run)

    2、定义多个子类,在子类中重写父类的方法(run),每个子类run方法实现不同的功能

    3、假设我们定义了一个函数,需要一个Base类型的对象的参数,那么调用函数的时候,传入Base类不同的子类对象,那么这个函数会执行不同的功能,这就是多态的体现。

    class Animal(object):
        '''定义一个Animal类'''
        def run(self):
            print("动物都会跑")
    
    class Cat(Animal):
        '''定义一个cat类,继承Animal'''
        def run(self):
            print("猫会跑")
    
    class Dog(Animal):
        '''定义一个Dog类,继承Animal'''
        def run(self):
            print("狗会跑")
    
    class Test():
        def run(self):
            print("Test类也有run方法")
    
    def func(obj):
        obj.run()
    
    #多态的意义是,根据不同的对象做不同的事情
    a=Animal()
    func(a)
    c=Cat()
    func(c)
    d=Dog()
    func(d)
    
    #---python的多态实际是一个伪多态,因为他不能像java那样定义数据类型,所以只有传入有run方法的类的对象,都能运行run方法
    t=Test()
    func(t)

    运行结果:

    动物都会跑
    猫会跑
    狗会跑
    Test类也有run方法

    python的多态实际是一个伪多态,因为他不能像java那样定义数据类型,所以只有传入有run方法的类的对象,都能运行run方法

  • 相关阅读:
    Web 2.0网站命名的7个建议
    梦猪课堂视频系列
    计算机英文术语完全介绍
    PPT高手的思路
    在线RSS阅读器大比拼
    【百度现有服务】
    转载VFW编程实例(详)
    实现MFC扩展DLL中导出类和对话框 (转)
    Windows下编译 OpenSceneGraph(转)
    OSG静态编译 (转)
  • 原文地址:https://www.cnblogs.com/crystal1126/p/13576865.html
Copyright © 2011-2022 走看看