Python教程

Python 多重继承

本文主要是介绍Python 多重继承,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

代码示例:

### 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()

结果:

"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()

 

这篇关于Python 多重继承的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!