Python的Mixin类学习

目录

Mixin 类

Mixin 类的实例

运行流程

流程图

《Python GUI Programming with Tkinter》作者的话


Mixin 类

Mixin 类只包含了一组特定的函数集合,而我们将会将其与其他类进行混合,从而生成一个适用于实际需要的新类

Mixin 类的实例

代码改编自《Python GUI Programming with Tkinter》

class Displayer():
    def display(self, message):
        print('2:display:Displayer')
        print(message)

class LoggerMixin():
    def log(self, message, filename='logfile.txt'):
        print('5:log:LoggerMixin')
        with open(filename, 'a') as fh:
            fh.write(message)

    def display(self, message):
        print('1:display:LoggerMixin')
        super().display(message)
        print('3:display:LoggerMixin')
        self.log(message)

class MySubClass(LoggerMixin, Displayer):
    def log(self, message):
        print('4:log:MySubClass')
        super().log(message, filename='subclasslog.txt')

subclass = MySubClass()
subclass.display("此字符串将显示并记录在subclasslog.txt中.")
E:\DataAnalysis\tools\python3\python.exe E:/DataAnalysis/tools/python3/project/money_analysis/text/object_test.py
1:display:LoggerMixin
2:display:Displayer
此字符串将显示并记录在subclasslog.txt中.
3:display:LoggerMixin
4:log:MySubClass
5:log:LoggerMixin

Process finished with exit code 0

运行流程

    '''In a multiple inheritance situation, super() does something a little more complex
than just standing in for the superclass. It look up the chain of inheritance using
 something called the Method Resolution Order and determines the nearest class that defines
 the method we’re calling.

    在多继承的环境下,super() 有相对来说更加复杂的含义。它会查看你的继承链,使用一种叫做 Methods
 Resolution Order(方法解析顺序) 的方式,来决定调用最近的继承父类的方法。'''

在我们调用 MySubClass.display() ,触发行为如下:

1.MySubClass.display() 方法被解析为 LoggerMixin.display() 方法的调用

对于 MySubClass 类来说,在继承链上有两个父类,LoggerMixin 最近,因此调用其方法。

2. LoggerMixin.display() 方法调用了 super().display()

在继承链上,是逐个继承的,后者是前者父类,查看运行结果,调用 Displayer 类的 display() 方法。

3.  LoggerMixin 类还调用了 self.log() 方法。

尽管self在LoggerMixin 语境中,但是由MySubClass 继承并调用,所以self指向MySubClass 实例,执行了MySubClass.log()

MySubClass.log() 执行 super().log() 方法,根据继承链寻找最近父类,执行了 LoggerMixin.log()

流程图

《Python GUI Programming with Tkinter》作者的话

   ''' If this seems confusing, just remember that self.method() will look for method() in
 the current class first, then follow the list of inherited classes from left to right 
until the method is found. The super().method() will do the same, except that it skips the 
current class.

如果这看起来很混乱,请记住self.method()将首先在当前类中查找method(),然后从左到右跟随继承类的
列表,直到找到该方法。super().method()将执行相同的操作,只不过它跳过了当前类。  '''

为什么要叫做 Mixin 类呢?

    '''Note that LoggerMixin is not usable on its own: it only works when combined with a 
class that has a display() method. This is why it’s a mixin class because it’s meant to be 
mixed in to enhance other classes.

也就是说,我们的 LoggerMixin 类是无法单独使用的,它必须要和一个拥有 display() 函数定义的类一起混合
使用。这也就是为什么它被称作是 Mixin 类的原因,它总是需要与其他类混合来加强其他类。'''

猜你喜欢

转载自blog.csdn.net/Da___Vinci/article/details/90666228