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
小甲鱼的讲解参考链接