python 继承和多态

继承

子类继承父类

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

class Dog(Animal):
    # 使程序结构完成,不报错
    pass

dog=Dog()
dog.run()
继承

子类继承父类,并覆盖父类

class Animal(object):
    def run(self):
        print('Animal is running...')
class Cat(Animal):
    # 子类有和父类一样的方法,子类覆盖父类
    def run(self):
        print('cat is running')
cat=Cat()
cat.run()
继承且覆盖

多态

多态
class Animal(object):
    def run(self):
        print('Animal is running...')


class Cat (Animal):
    # 子类有和父类一样的方法,子类覆盖父类
    def run(self):
        print('cat is running..')


class Dog(Animal):
    # 使程序结构完成,不报错 pass
    def run(self):
        print('dog is running...')


def run_twice(animal):
    animal.run()
    animal.run()
run_twice(Animal())

动态语言

class Timer(object):
    def run(self):
        print('start...')

def run_twice(animal):
    animal.run()
    animal.run()
run_twice(Timer())

你可能感兴趣的:(python 继承和多态)