子类覆盖父类的方法

时间:2021-07-02 19:29:29
当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。

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


子类:

from mycompany.web.Animal import *
class Dog(Animal):
def run(self):
print 'Dogxx is running...'
print 'yy'

a1.py:

from mycompany.web.Dog import *
dog = Dog()
dog.run()

C:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/a1.py
yy
Dogxx is running.