Mixins
写自己代码的时候不推荐mixin,但是做framework的时候可以用

# -*- coding:utf-8 -*-
class Connection():
def __init__(self):
self.connection = ''
def connect(self):
print('We are connecting from ' + self.connection)
class Loggable():
def __init__(self):
self.server = ''
def log(self):
print('Logging from ' + self.server)
# define a framework
def framework(item):
if isinstance(item, Connection):
item.connect()
if isinstance(item, Loggable):
item.log()
# define a sql connection
class Sql(Connection, Loggable):
def __init__(self):
super().__init__()
self.connection = 'postgres DB'
self.server = 'unknown Flask server'
mysql = Sql()
framework(mysql)
We are connecting from postgres DB
Logging from unknown Flask server
小甲鱼的讲解参考链接
文章介绍了Mixins在Python中的应用,通过一个实例展示了如何使用Mixins结合多重继承创建一个Sql类,该类同时具备连接数据库和日志记录的功能。在个人编码时不推荐频繁使用Mixins,但在构建框架时可以利用其灵活性。

1753

被折叠的 条评论
为什么被折叠?



