1.多继承
class A:
def get_a(self):
print 'a'
class B:
def get_b(self):
print 'b'
class C(A, B):
pass
c = C()
c.get_a()
c.get_b()
2.python的元编程特性
A.__bases__ += (B,)
a.get_b()
实际上等同于: class C:
pass
C.__bases__ += (A, B, )
3.方式三:可以使用插件的方式,只是修改对象的行为而不是类的行为的。这样的话,可以更加好的便于扩展操作的
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()
网友评论