Python 多重继承
多重继承,多继承
多重继承代码示例:
### ref https://zhuanlan.zhihu.com/p/97995434 class A: def func1(self): print("in A func1") def func2(self): print("in A func2") class B: def func2(self): print("in B func4") def func3(self): print("in B func3") class C(A, B): pass c = C() print(c.func1()) # in func1 print(c.func2()) # in func2 print(c.func3()) # in func3 # 原因解析: # 1.c 是类 C 的一个实例化对象,C 中没有任何内容 # 2.c.func1(),先从父类 A 中找,找不到再从父类 B 中找 # 3.同理,c.func3()、c.func2() 查找顺序一样 # 4.因为父类 A 中有 func2 方法,因此 c.func2() 执行的是父类 A 中的
结果
in A func1 None in A func2 None in B func3 None
代码示例:
### ref https://www.cnblogs.com/jiangzuofenghua/p/11413777.html class Printable: def _print(self): print(111,self.content) class Document: #第三方库,不允许修改 def __init__(self,content): self.content = content class Word(Document): pass #第三方库,不允许修改 class PrintableWord(Printable,Word): pass print(222,PrintableWord.__dict__) print(333,PrintableWord.mro()) pw = PrintableWord('test string') pw._print()
print(dir(PrintableWord))
结果:
"D:\Program Files\python_3_6_4\python.exe" D:/untitled2/xdemo.py 222 {'__module__': '__main__', '__doc__': None} 333 [<class '__main__.PrintableWord'>, <class '__main__.Printable'>, <class '__main__.Word'>, <class '__main__.Document'>, <class 'object'>] 111 test string
代码示例:
#### ref https://blog.csdn.net/u013008795/article/details/90412084
def printable(cls): def _print(self): print(self.content,'装饰器') cls.print = _print return cls class Document: #第三方库,不允许修改 def __init__(self,content): self.content = content class Word(Document): pass #第三方库,不允许修改 @printable #先继承,后装饰 class PrintableWord(Word): pass print(PrintableWord.__dict__) print(PrintableWord.mro()) pw = PrintableWord('test string') pw.print()
print(dir(PrintableWord))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
2021-01-25 Windows 10 安装PyTorch (无GPU)
2021-01-25 Pycharm 安装 numpy
2010-01-25 常用商品条形码简介和成员国前缀码
2010-01-25 常见条形码简介