我有这样定义的3个类:
class Device:
Some method
class SSH:
def connect(self,type):
# code
def execute(self,cmd):
# code
class Netconf:
def connect(self,type):
# code
def execute(self,cmd):
# code
注意SSH和Netconf类具有相同的方法名称,但它们以不同的方式执行操作。 我有类Device的实例,并希望访问这样的方法 -
d = Device()
d.connect('cli') # <-- This should call SSH method and subsequently
# d.execute(cmd) should call execute method from SSH class
# too.
d.connect('netconf') # <-- This should call Netconf method and subsequently
# d.execute(cmd) should call execute method from
# Netconf class too.
问题是 - 我该如何实现?我希望能够在Device类实例上使用SSH / Netconf类的方法&#39; d&#39;基于输入。
答案 0 :(得分:1)
您可以通过存储在私有Device
属性中连接的设备类型,然后通过添加自定义__getattr__()
方法将大多数方法调用转发给它来实现此目的。这在connect()
方法中有点棘手,因为这是定义了目标设备(而不是Device.__init__()
初始化程序)。
我还将名为type
的变量更改为kind
,以避免与同名的内置模块发生冲突。
class Device(object):
def connect(self, kind):
if kind == 'cli':
target = self._target = SSH()
elif kind == 'netconf':
target = self._target = Netconf()
else:
raise ValueError('Unknown device {!r}'.format(kind))
return target.connect(kind)
def __getattr__(self, name):
return getattr(self._target, name)
class SSH(object):
def connect(self, kind):
print('SSH.connect called with kind {!r}'.format(kind))
def execute(self, cmd):
print('SSH.execute called with cmd {!r}'.format(cmd))
class Netconf(object):
def connect(self, kind):
print('Netconf.connect called with kind {!r}'.format(kind))
def execute(self, cmd):
print('Netconf.execute called with cmd {!r}'.format(cmd))
d = Device()
d.connect('cli')
d.execute('cmd1')
d.connect('netconf')
d.execute('cmd2')
输出:
SSH.connect called with kind 'cli'
SSH.execute called with cmd 'cmd1'
Netconf.connect called with kind 'netconf'
Netconf.execute called with cmd 'cmd2'
答案 1 :(得分:0)
您应该实施Strategy Pattern。 connect()
方法应该实例化适当的类(如果需要,从前一个detach()
)并存储它,然后其他方法应该委托给存储的对象。