不太理解,老师说只要是animal的子类或者animal,但是亲测只要有run方法都可以啊
Topic source这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。
Python的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。
- 1
Young先森森
class Animal(object): """docstring for Animal""" def init(self): super(Animal, self).init()
class Dog(Animal): """docstring for Dog""" def init(self): super(Dog, self).init()
class Cat(Animal): """docstring for Cat""" def init(self): super(Cat, self).init()
class Tortoise(Animal): """docstring for Tortoise""" def init(self): super(Tortoise, self).init()
class Temp(object): """docstring for Temp""" def init(self): super(Temp, self).init()
def run_twice(animal): animal.run() animal.run()
run_twice(Dog()) print('------------') run_twice(Cat()) print('------------') run_twice(Tortoise()) print('------------') run_twice(Temp())
打印结果 Dog is running
Dog is running
Cat is running
Cat is running
Tortoise is run slowly
Tortoise is run slowly
Temp... Temp...