概述
面向对象三大特性:封装,继承和多态,
从字⾯理解就是多种形态 ⼀个对象可以以不同形态去呈现
⾯向对象三⼤特性:
- 封装 :确保对象中数据的安全
- 继承 :保证了对象的扩展性
- 多态 :保证了程序的灵活性
前面博客讲了封装,而这一章博客来讲讲继承,与多态
继承
继承提⾼了类的复⽤性。让类与类之间产⽣了关系。有了这个关系,才有了 多态的特性
在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)
代码实战说明
# 垃圾类 父类
class Waste():
w_name = '垃圾'
# ‘垃圾’类的一个方法:回收垃圾
def recycle_w(self):
print('回收垃圾...')
# ‘有害垃圾’类 子类1
class Swaste(Waste): # 括号中填写父类的变量名
pass
# ‘可回收垃圾’类 子类2
class Gwaste(Waste):
pass
继承有什么好处?最大的好处是子类获得了父类的全部功能。Swaste和Gwaste就继承了Waste的全部功能
如下运行试试:
a1 = Waste() #实例化父类Waste
a2 = Swaste() #实例化子类1Swaste
a3 = Gwaste() #实例化子类2Gwaste
a1.recycle() #在父类中调用recycle()方法
a2.recycle() #在子类1中调用recycle()方法
a3.recycle() #在子类2中调用recycle()方法
结果为:
回收垃圾...
回收垃圾...
回收垃圾...
虽然Swaste和Gwaste两个类中没有实质代码块内容,但是他们继承了Waste类的功能,所以可以运行recycle()
# 垃圾类
class Waste():
w_name = '垃圾'
# ‘垃圾’类的一个方法:回收垃圾
def recycle(self):
print('回收垃圾...')
# ‘有害垃圾’类
class Swaste(Waste): # 括号中填写父类的变量名
def run1(self):
print('处理有害垃圾')
# ‘可回收垃圾’类
class Gwaste(Waste):
def run2(self):
print('回收可回收垃圾')
a1 = Waste() #实例化父类Waste
a2 = Swaste() #实例化子类1Swaste
a3 = Gwaste() #实例化子类2Gwaste
a1.recycle() #在父类中调用方法recycle()
a2.recycle() #在子类1中调用方法recycle()
a2.run1() #在子类1中调用方法run1()
a3.recycle() #在子类2中调用方法recycle()
a3.run2() #在子类2中调用方法run1()