|
发表于 2017-3-9 23:19:09
|
显示全部楼层
class PlugIn(object):
def __init__(self):
self._exported_methods = [] #初始化 输出的方法
def plugin(self, owner):
for f in self._exported_methods: #对每一个输出的方法 在字典里扩充
owner.__dict__[f.__name__] = f
def plugout(self, owner):
for f in self._exported_methods: #去掉输出的方法
del owner.__dict__[f.__name__]
class AFeature(PlugIn):
#继承 插件 必须由PlugIn 否者报错[super() argument 1 must be type, not classobj]
def __init__(self):
super(AFeature, self).__init__()
#格式就是如此 也可以删掉super()括号中的内容
'''super(AFeature, self).__init__() :super(AFeature, self)
首先找到AFeature的父类(就是类PlugIn)
,然后把类AFeature的对象self转换为类PlugIn的对象
然后“被转换”的类PlugIn对象调用自己的__init__函数。'''
self._exported_methods.append(self.get_a_value)
#这里直接将PlugIn的sel._exported_methods 移过来!
#self.get_a_value 不能去掉self, 这个函数也需要self来指向。
#通过AFeature().plugin(c) 将 get_a_value存入字典中 形式为c.get_a_value(owner.__dict__[f.__name__])
#c.get_a_value = self.get_b_value 这时候的self B->A , 调用就可以A调用B的 self.get_b_value!
def get_a_value(self):
print ('a feature.')
class BFeature(PlugIn):
def __init__(self):
super(BFeature, self).__init__()
self._exported_methods.append(self.get_b_value)
def get_b_value(self):
print ('b feature.')
class Combine:
pass
c = Combine()
AFeature().plugin(c)
BFeature().plugin(c)
#将AB 中的方法 像“插件”的形式插入到c中。
c.get_a_value()
c.get_b_value()
'''
1. super并不是一个函数,是一个类名,形如super(B, self)事实上调用了super类的初始化函数,
产生了一个super对象;
2. super类的初始化函数并没有做什么特殊的操作,只是简单记录了类类型和具体实例;
3. super(B, self).func的调用并不是用于调用当前类的父类的func函数;
4. Python的多继承类是通过mro的方式来保证各个父类的函数被逐一调用,而且保证每个父类函数
只调用一次(如果每个类都使用super);
5. 混用super类和非绑定的函数是一个危险行为,这可能导致应该调用的父类函数没有调用或者一
个父类函数被调用多次。''' |
|