|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 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):
- def __init__(self):
- super(AFeature, self).__init__()
- self._exported_methods.append(self.get_a_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)
- c.get_a_value()
- c.get_b_value()
复制代码
1.第7行那里是字典在添加键对值吗?这里__dict__是啥意思??
是的; __dict__ 是 Python 的内置属性,可以查看当前对象中所拥有的属性,以键值对表示,所以这里赋值相当于给 owner 对象中添加新的键,即添加新的对象
2.第16行那里self.get_a_value后面不用加()吗?
加上 () 表示函数调用结果,而这里不加括号表示将函数体加入到列表中去,因为后续 for 循环会向函数体的对象通过 __dict__ 赋值添加方法对象,所以这里不用加上括号
3.第32、33那两行是什么意思。。类后面为啥加了个括号
类加括号就是实例化类呀,只是没有赋值给具体变量
4.没懂c是怎么继承到AFeature BFeature的方法的??
通过 AFeature().plugin(c) , BFeature().plugin(c) 的调用,然后 for 循环,通过 __dict__ 中添加了方法对象
|
|