gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:31:08 24 4
gpt4 key购买 nike

我的程序使用 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())

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

最佳答案

更经典的方法是用您自己的类包装 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...

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

关于python - 如何找出 Python 中嵌套函数的调用者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22118250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com