python进阶,在第一期的基础上做了极大的优化,整体更加美观易懂 内容较多(该篇幅超过4000字),分为上下两个篇幅,此篇是上
十九、继承 (上)
继承:继承是基于面向对象础知识点的,继承有单继承和多继承
19.1、继承作用
继承的作用:节省代码
# 经典类:
class 类名:
代码
# 新式类:
class 类名(objetc):
代码
class Abc(object):
def __init__(self):
self.num = 10
def info_print(self):
print(self.num)
class Bcd(Abc):
pass
duixiang = Bcd()
duixiang.info_print()
>>> 10
19.1.1、单继承
单继承:指的是一个父类继承给一个子类(一对一的继承)
class Master():
def __init__(self):
self.fu = "i is you father"
def tudi(self):
print(f"{self.fu} = 我是你**")
class Su(Master):
pass
duxiiang = Su()
print(duxiiang.fu)
duxiiang.tudi()
>>> i is you father
>>> i is you father = 我是你**
19.1.2、多继承
多继承(一个子类同时继承多个父类)
class Master(object):
def __init__(self):
self.fu = "i is you fathe"
def zi(self):
print(f"{self.fu} = 我是你**")
class Fath(object):
def __init__(self):
self.back_fatc = "i is two fath"
def zi_0(self):
print(f"{self.back_fatc} = 我是你后**")
class Su(Master, Fath):
pass
duxiang = Su()
print(duxiang.fu)
duxiang.zi()
duxiang_0 = Fath()
print(duxiang_0.back_fatc)
duxiang_0.zi_0()
>>> i is you fathe
>>> i is you fathe = 我是你**
>>> i is two fath
>>> i is two fath = 我是你后**
所谓的多继承就是一个子类继承多个父类,是一对多的继承
重写(子类和父类)
class Fath_1(object):
def __init__(self):
self.back_fatc = "张三的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学走了")
class Fath_2(object):
def __init__(self):
self.back_fatc = "张三徒弟的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学会了")
class Su(Fath_1, Fath_2):
def __init__(self):
self.back_fatc = "自创的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学会了")
wangwu = Su()
print(wangwu.back_fatc)
wangwu.zi_0()
结果:
>>> 自创的拿手手艺
>>> 自创的拿手手艺我学会了
> 1、如果子类和父类有同名的属性和方法,通过子类创建对象去调用到的是子类里面的同名属性和方法
> 2、所谓的重写就是在子类当中去重写父类的同名属性和方法 ```
class Fath_1(object):
def __init__(self):
self.back_fatc = "张三的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学走了")
class Fath_2(object):
def __init__(self):
self.back_fatc = "张三徒弟的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学会了")
class Su(Fath_1, Fath_2):
def __init__(self):
self.back_fatc = "自创的拿手手艺"
def zi_0(self):
print(f"{self.back_fatc}我学会了")
def make_fath_1(self):
Fath_1.__init__(self)
Fath_1.zi_0(self)
def make_fath_2(self):
Fath_2.__init__(self)
Fath_1.zi_0(self)
wangwu = Su()
print(wangwu.back_fatc)
wangwu.zi_0()
wangwu.make_fath_1()
wangwu.make_fath_2()
>>> 自创的拿手手艺
>>> 自创的拿手手艺我学会了
>>> 张三的拿手手艺我学走了
>>> 张三徒弟的拿手手艺我学走了
|