【发布时间】:2011-04-13 07:00:54
【问题描述】:
我有一个基类,我想在其中处理 __add__() 并希望在 __add__ 处理两个子类实例时支持 - 即在结果实例中具有两个子类的方法。
import copy
class Base(dict):
def __init__(self, **data):
self.update(data)
def __add__(self, other):
result = copy.deepcopy(self)
result.update(other)
# how do I now join the methods?
return result
class A(Base):
def a(self):
print "test a"
class B(Base):
def b(self):
print "test b"
if __name__ == '__main__':
a = A(a=1, b=2)
b = B(c=1)
c = a + b
c.b() # should work
c.a() # should work
编辑:更具体地说:我有一个类Hosts,它拥有一个dict(host01=.., host02=..)(因此是dict 的子类) - 这提供了一些基本方法,例如@ 987654327@
现在我有一个子类HostsLoadbalancer 包含一些特殊方法,例如drain(),我有一个类HostsNagios 包含一些特定于nagios 的方法。
然后我正在做的事情是这样的:
nagios_hosts = nagios.gethosts()
lb_hosts = loadbalancer.gethosts()
hosts = nagios_hosts + lb_hosts
hosts.run_ssh_command_on_all_hosts('uname')
hosts.drain() # method of HostsLoadbalancer - drains just the loadbalancer-hosts
hosts.acknoledge_downtime() # method of NagiosHosts - does this just for the nagios hosts, is overlapping
这个问题的最佳解决方案是什么?
我想我可以以某种方式“复制所有方法”——就像这样: 对于 dir(other) 中的 x: setattr(self, x, getattr(other, x))
我在正确的轨道上吗?还是应该使用抽象基类?
【问题讨论】:
标签: python multiple-inheritance