继承:
class p : cls_name = 'p' def __init__(self): print('正在实例化') def __del__(self): print('正在销毁') class cb(p): # 当前类继承()中类 pass c = cb() print(c)
重写:
class p : cls_name = 'p' def __init__(self): print('正在实例化') def __del__(self): print('正在销毁') class cb(p): # 当前类继承()中类 def __init__(self): ## 在子类中 重写 方法 print('正在实例化子类') c = cb() print(c)
多继承
一个类可以继承另一个类,继承之后,他就可以用这个类(父类)的方法和属性,
且类可以继承多个类,
在继承多个类中,如果多个父类的中有一样的方法,继承第一个类中的方法,
class pa :
cls_name = 'p'
def __init__(self):
print('正在实例化')
def __del__(self):
print('正在销毁')
class pb :
cls_name = 'p'
def __init__(self):
print('正在实例化')
def __del__(self):
print('正在销毁')
class cb(pa,pb): # 当前类继承()中类
pass
c = cb() # 继承多个父类,且中有相同方法,则继承第一个类中的方法,
print(c)
多继承后子类调用父类的二个方法:
class ParentA: def a(self): print('这是个ParentA的类') class ParentB: def a(self): print('这是个ParentB的类') class Child(ParentA,ParentB): def a(self): ParentB.a(self) # 方法 1 ,直接调用, ParentA.a(self) super().a() # 方法 2 ,用 super 调用, super(ParentA,self).a() # 些时调用的是 A 的下一个, print('这是个ChildB的类') x = Child() x.a()
super用法,:默认调用第一顺序位的父类方法,
可以通过给其参数,来确定调用哪个父类方法,
如:super(ParentA,self).a() # 些时调用的是 A 的下一个,
在定义类时,内部会计算出个方法解释顺序,mro列表,其是个简单的所有基类的顺序列表,
print(x.__mro__) x是实例名 直到 'object'
调用方法时:
1 子类先父类,
2 多个父类就按mro顺序
2 下个类存在两个合法选择,左先于右
魔术方法:
实例拼接
# 实例拼接
class A:
def __add__(self, other):
print('A 的 add 方法')
class B:
def __add__(self, other):
print('B 的 add 方法')
a = A()
b = B()
a + b
————》》》 A 的 add 方法
str 方法: 在测试中可常用
class C:
def __str__(self):
print('C 的 str 方法')
return 'str 返回值' # 这里必须有返回值
s = C()
print(s)
————》》》》》
C 的 str 方法
str 返回值
repr, 当有 str 时不会触发repr
class C:
# def __str__(self):
# print('C 的 str 方法')
# return 'str 返回值'
def __repr__(self):
print('C 的 repr 方法')
return 'repr 返回值'
s = C()
print(s)
str(s)
——————》》》
C 的 repr 方法
repr 返回值
call 方法
class C:
# def __str__(self):
# print('C 的 str 方法')
# return 'str 返回值'
def __repr__(self):
print('C 的 repr 方法')
return 'repr 返回值'
def __call__(self, *args, **kwargs):
print('一在调用 call 方法')
s = C()
# 实例()触发 call 方法,如果没有该方法,会报错
s()



补充:接口继承:
# 接口继承:
import abc
class All_file ( metaclass = abc.ABCMeta ):
@ abc.abstractclassmethod # 这下边的方法不用具体实现,
def read(self):
pass
@ abc.abstractclassmethod
def write(self):
pass
class Disk(All_file):
def read(self):
print('disk,read')
def write(self):
print('disk,write')
class Cdrom(All_file):
def read(self):
print('cdrom,read')
def write(self):
print('cdrom,write')
class Mem(All_file):
def read(self):
print('mem,read')
def write(self):
print('mem,write')
m1 = Mem()
# 接口就是一个函数,接口继承:定义个基类, 基类中把自己的方法,
# 定义居接口,@ abc.abstractclassmethod,让继承的子类必须实现接口方法,
# 不实现,不能实例化,
以一切皆文件为例,做 读 写 的操作,定义个父类,作用在于规范子类,无需实现具体功能,
让其他硬件 如 硬盘,光盘 ,内存 为子类继承父类 (读写)要求,
如功能缺失,不能实例化