zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    动态规划3-最长公共子序列问题
    动态规划2-最大子段和
    动态规划1- 矩阵取数
    javac编译提示错误需要为 class、interface 或 enum
    [core python programming]chapter 7 programming MS office
    ubuntu apache nginx 启动 关闭
    ubuntu 安装 hustoj
    TCP报文段的首部格式
    守护进程
    会话session
  • 原文地址:https://www.cnblogs.com/emanlee/p/15844692.html
Copyright © 2011-2022 走看看