python动态继承类



是否可以在python中进行动态继承?我正试图在运行时根据参数device_typeconnection_typeSuperSwitch类中选择一个netmiko类

如有任何帮助,将不胜感激

例如:

mapper = {
'juniper': {
'telnet': JuniperTelnet,
'ssh': JuniperSSH
},
'cisco': {
'telnet': CiscoIosTelnet,
'ssh': CiscoIosSSH
}
}
class SuperSwitch:
def __init__(self, device_type, connection_type, ip, port, user, pw):
# how can I dynamically inherit the class based on the device_type and connection_type
# for example mapper['juniper']['telnet']
device_args = dict(
device_type='{d}_{conn}'.format(p=device_type, conn=connection_type),
ip=ip,
port=port,
username=user,
password=pw,
)
super().__init__(**device_args)
def my_send_command(self, cmd):
print("running:", cmd)
super().send_command(cmd)

class MyJuniper(SuperSwitch):
def __init__(self, device_type, connection_type, ip, port, user, pw):
super().__init__(device_type, connection_type, ip, port, user, pw)
def my_send_command(self, cmd):
super().my_send_command(cmd)
# my other code

sw = MyJuniper('juniper', 'telnet', '10.0.0.2', 1234, 'user', 'pw')
sw.my_send_command('show ?')

我认为你做不到,或者至少我不知道你怎么能做到。但是你可以将你的实现隐藏在超级开关中,这就是类的作用。

mapper = {
'juniper': {
'telnet': JuniperTelnet,
'ssh': JuniperSSH
},
'cisco': {
'telnet': CiscoIosTelnet,
'ssh': CiscoIosSSH
}
}
class DummyImplementation():

def __init__(self, **kwargs):
self.args = kwargs

def send(self, cmd):
print(cmd)
def get_right_implementation(device_type, connection_type):
# do you magic!
return DummyImplementation
class SuperSwitch:
def __init__(self, device_type, connection_type, ip, port, user, pw):
# how can I dynamically inherit the class based on the device_type and connection_type
# for example mapper['juniper']['telnet']
implementation_class = get_right_implementation(device_type, connection_type)
device_args = dict(
device_type='{d}_{conn}'.format(p=device_type, conn=connection_type),
ip=ip,
port=port,
username=user,
password=pw,
)
self.implementation = implementation_class(**device_args)

def my_send_command(self, cmd):
self.implementation.send(cmd)

最新更新