Discuss / Python / 敲代码练练手

敲代码练练手

Topic source
# -*- coding: utf-8 -*-
class Animal(object):
    def run(self):
        print('Animal running....')

class Dog(Animal):
    def run(self):
        print('Dog running...')

class Cat(Animal):
    def run(self):
        print('Cat running')

#定义一个有run方法但不是继承Animal        
class Timer(object):
    def run(self):
        print('滴滴滴。。。')

#多态,只需要传入的对象有run方法即可!
def run_twice(objHasRun):
    objHasRun.run()
    objHasRun.run()

#测试    
run_twice(Animal())
run_twice(Cat())
run_twice(Dog())
run_twice(Timer())

在java中实现多态,要求是父类的引用指向子类的变量,在python中,由于定义变量时没法指定属于哪种类型,所以要求‘看起来像鸭子’即可。

_路人07

#2 Created at ... [Delete] [Delete and Lock User]

感觉是一种protocol的意思,只要符合protocol(有run函数),就可以调用

一楼讲的挺好的


  • 1

Reply