[英]python dynamically inherit class
是否可以在 python 中進行動態 inheritance? 我正在嘗試SuperSwitch
在運行時並基於參數device_type
和connection_type
任何幫助,將不勝感激
例如:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.