Discuss / Python / 继承多态

继承多态

Topic source

Kiah

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

#继承, 多态

class Animal(object):

    def run(self):

        print('Animal is running...')

class Dog(Animal):

    def run(self):

        print('Dog is running...')

class Cat(Animal):

    def run(self):

        print('Cat is running...')

def run_by_animal(animal):

    if isinstance(animal,Animal):

        print(type(animal))

        animal.run()

d = Dog()

c = Cat()

run_by_animal(d)

run_by_animal(c)

class Giao(object):# 它并没有继承 Animal

    def run(self):

        print("giao has run method. ...")

# 对python这种动态语言来说, 传入的对象可以不是 Animal类型, 只要有 run() 方法就可以使用

def run_has_run(obj):

    obj.run()

g = Giao()

run_has_run(g)


  • 1

Reply