python中的关于mixin的两个例子
参考:https://blog.csdn.net/appleyuchi/article/details/105733270
有时间多看几遍,不难理解
例子1
class Role: def walk(self): print('走') class RunMixin: def run(self): print('跑') class PromptSkillMixin: def use_prompt_skill(self): print('使用了一个瞬发技能') class WalkExMixin:#覆盖Role中的功能,因为下面是最先继承,Role是最后继承 def walk(self): print('疾走') class RoleEx(WalkExMixin, PromptSkillMixin, RunMixin, Role): def marco(self): return [self.run, self.use_prompt_skill] def use_marco(self): print("---------------use_marco技术----------------") for action in self.marco(): action() print("--------use_marco结束----------") if __name__ == '__main__': r = RoleEx() r.use_marco() r.walk()
输出如下
---------------use_marco技术----------------
跑
使用了一个瞬发技能
--------use_marco结束------------------
疾走
例子2
class Displayer(): def display(self, message): print("--------②这里是Displayer.display函数---start-----") print("Displayer的self=", self) print(message) print("--------②这里是Displayer.display函数---end-----\n") class LoggerMixin(): def log(self, message, filename='logfile.txt'): print("MySubClass self=", self) with open(filename, 'a') as fh: print("--------③这里是LoggerMixin.log函数---start-----") fh.write(message) print("--------③这里是LoggerMixin.log函数---end-----\n") def display(self, message): print("display的self=", self) # 这里的self类指代的是MySubClass,并不是LoggerMixin print("------①这里是LoggerMixin的display函数-start--\n") super().display(message) # 会调用Displayer.display()函数 self.log(message) print("------①这里是LoggerMixin的display函数-end--\n") class MySubClass(LoggerMixin, Displayer): def log(self, message): super().log(message, filename='subclasslog.txt') subclass = MySubClass() print(MySubClass.__mro__) subclass.display("This string will be shown and logged in subclasslog.txt")
输出如下,使用了魔法函数__mro__, 可以看出复杂类的继承顺序。主要关注LoggerMixin类中display函数里的super().display(message)
(<class '__main__.MySubClass'>, <class '__main__.LoggerMixin'>, <class '__main__.Displayer'>, <class 'object'>) display的self= <__main__.MySubClass object at 0x0000024EB6FE05F8> ------①这里是LoggerMixin的display函数-start-- --------②这里是Displayer.display函数---start----- Displayer的self= <__main__.MySubClass object at 0x0000024EB6FE05F8> This string will be shown and logged in subclasslog.txt --------②这里是Displayer.display函数---end----- MySubClass self= <__main__.MySubClass object at 0x0000024EB6FE05F8> --------③这里是LoggerMixin.log函数---start----- --------③这里是LoggerMixin.log函数---end----- ------①这里是LoggerMixin的display函数-end--
LoggerMixin
努力生活,融于自然