继承:实现代码的重用,相同的代码不需要重复写
1.子类继承自父类,可以直接享受父类中已经封装好的方法。class Animal(): #父类
def eat(self):
print('吃~~~~~')
def drink(self):
print('喝')
def run(self):
print('跑')
def sleep(self):
print('睡')
class Cat(Animal): #子类继承父类
def call(self):
print('喵~')
fentiao = Cat()
fentiao.eat() #子类可以调用父类的方法
fentiao.run()
fentiao.call()
运行结果:
吃~~~~~
跑
喵~
2.继承具有传递性,子类拥有父类的父类的属性和方法
class Animal():
def eat(self):
print('吃~~~~~')
def drink(self):
print('喝')
def run(self):
print('跑')
def sleep(self):
print('睡')
class Cat(Animal):
def call(self):
print('喵~')
class HelloKitty(Cat):
def speak(self):
print('我能说英语')
kt = HelloKitty()
kt.eat()
kt.speak()
kt.call()
运行结果:
吃~~~~~
我能说英语
喵~
3.同时有两个父类:
class A():
def test(self):
print('A---->test方法')
def demo(self):
print('A---->demo方法')
class B():
def test(self):
print('B---->test方法')
def demo(self):
print('B---->demo方法')
class C(A,B):
pass
c = C()
c.test()
c.demo()
运行结果:
A---->test方法
A---->demo方法
多态
如果子类重写了父类的方法。
在运行时,只会调用在子类中重写的方法而不会调用父类方法。
多态体现了勃兰特梅耶提出的开闭原则:软件实体应对外扩展开放,对修改关闭。
class Animal():
def eat(self):
print('吃~~~~~')
def drink(self):
print('喝')
def run(self):
print('跑')
def sleep(self):
print('睡')
class Cat(Animal):
def call(self):
print('喵~')
class HelloKitty(Cat):
def speak(self):
print('我能说英语')
def call(self):
print('@#@$@$@#@!#')
kt = HelloKitty()
kt.call()
运行结果:@#@$@$@#@!#
2.同时调用子类方法和父类方法
class Animal():
def eat(self):
print('吃~~~~~')
def drink(self):
print('喝')
def run(self):
print('跑')
def sleep(self):
print('睡')
class Cat(Animal):
def call(self):
print('喵~')
class HelloKitty(Cat):
def speak(self):
print('我能说英语')
def call(self):
# 1.针对子类特有的需求,编写代码
print('@#@$@$@#@!#')
# 2.调用原本在父类中封装的方法
Cat.call(self)
super().call()
kt = HelloKitty()
kt.call()
运行结果:
@#@$@$@#@!#
喵~
喵~