Discuss / Python / 不太理解,老师说只要是animal的子类或者animal,但是亲测只要有run方法都可以啊

不太理解,老师说只要是animal的子类或者animal,但是亲测只要有run方法都可以啊

Topic source

class Animal(object): """docstring for Animal""" def init(self): super(Animal, self).init()

    # self.arg = arg
def run(self):
    print('Animal is running')

class Dog(Animal): """docstring for Dog""" def init(self): super(Dog, self).init()

    # self.arg = arg
def run(self):
    print('Dog is running')

class Cat(Animal): """docstring for Cat""" def init(self): super(Cat, self).init()

    # self.arg = arg
def run(self):
    print('Cat is running')

class Tortoise(Animal): """docstring for Tortoise""" def init(self): super(Tortoise, self).init()

    # self.arg = arg
def run(self):
    print('Tortoise is run slowly')

class Temp(object): """docstring for Temp""" def init(self): super(Temp, self).init()

    # self.arg = arg
def run(self):
    print('Temp...')

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...

都说了,这叫多态

这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。

Python的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。

Hsakei

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

python的函数传入的参数是没有类型的,而静态语言像c++,一个函数传入的参数类型必须是确定的,比如 int f(int a, char c)


  • 1

Reply