如何在Python中找出嵌套函数的调用者

2024-09-27 00:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序使用Telnet和SNMP与网络设备通信。Telnet和SNMP对于相同的功能有不同的命令,例如清除设备的配置。我需要从实际设备中抽象出我的测试逻辑,所以我使用如下硬件抽象层:

#ClearConfigCommand is an interface I use in my tests
def ClearCongifCommand(type = 'cli')
    if type == 'cli':
        return 'clear config'
    elif type == 'snmp':
        return 'oid and some more information'

在我的程序中,我使用SNMP和Telnet发送如下命令:

#Create connection to the device
cTelnet = Telnet('192.168.1.2')
cTelnet.Send(ClearConfigCommand())
cSNMP = SNMP('192.168.1.2')
cSNMP.Send(ClearConfigCommand('snmp'))

ClearConfigCommand()是否可以知道我使用的是哪种类型的连接,这样我就不需要向它传递“snmp”参数了?我想要的代码是:

#Create connection to the device
cTelnet = Telnet('192.168.1.2')
cSNMP = SNMP('192.168.1.2')
cTelnet.Send(ClearConfigCommand())
#We don't 
cSNMP.Send(ClearConfigCommand())

我尝试使用stack,但没有成功,因为ClearConfigCommand()在Send()之前被调用,所以我无法判断哪个对象(Telnet或SNMP)正在使用ClearConfigCommand()的输出


Tags: to命令程序sendclireturntypecreate
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:02

更经典的方法是用您自己的类包装TelnetSNMP类,提供ClearConfigCommand()

class MyTelnet(Telnet):
    def ClearConfigCommand(self):
        self.Send('clear config')

class MySNMP(SNMP):
    def ClearConfigCommand(self):
        self.Send('oid and some more information')

cTelnet = MyTelnet('192.168.1.2')
cTelnet.ClearConfigCommand()
etc...

这样,除了要添加的功能外,您的类还具有原始类的所有功能

相关问题 更多 >

    热门问题