继承定义:我们定义一个类的时候,可以从某个现有的类继承,新的类称为子类,而被继承的类称为基类、父类或超类。
最大的好处是子类获得了父类的全部功能。例如:
class Animal(object):
def run(self):
print('Animal is running ')
def eat(self):
print('Animal is eating ')
class Dog(Animal):
pass
dog1 = Dog()
dog1.eat()#Animal is running
dog1.run()#Animal is eating
第二个好处需要我们对代码做一点改进 重写父类的方法,是方法具有新的功能,例如:
class Animal(object):
def run(self):
print('Animal is running ')
def eat(self):
print('Animal is eating ')
class Dog(Animal):
def run(self):
print('Dog is running')
def eat(self):
print('Dog is eating')
dog1 = Dog()
dog1.eat() #Dog is running
dog1.run() #Dog is eating
当子类和父类都存在相同的方法时,我们说,子类的重写了父类的方法,在代码运行的时候,总是会调用子类的重写后的方法。这就是继承的另一个好处:多态。
class Animal(object):
def run(self):
print('Animal is running ')
def eat(self):
print('Animal is eating ')
class Dog(Animal):
def run(self):
print('Dog is running')
def eat(self):
print('Dog is eating')
animal = Animal()
def anial_action(animal):
animal.run()
animal.eat()
anial_action(Animal())
anial_action(Dog())
#定义新的Animal子类Cat类, 你会发现,新增一个Animal的子类,不必对anial_action()做任何修改,
#实际上,任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态。
class Cat(Animal):
def run(self):
print('Cat is running ')
def eat(self):
print('Cat is eating ')
anial_action(Cat())
网友评论