gpt4 book ai didi

inheritance - 匿名类继承

转载 作者:太空狗 更新时间:2023-10-30 00:30:34 25 4
gpt4 key购买 nike

我正在围绕看起来像这样的设备配置构建一个 python 自动化 API...

root@EX4200-24T# show interfaces ge-0/0/6 
mtu 9216;
unit 0 {
family ethernet-switching {
port-mode trunk;
vlan {
members [ v100 v101 v102 ];
}
}
}

root@EX4200-24T#

我正在为某些操作(如 SET)定义 python 类,以及为该操作的关键字定义类...想法是 SET 将遍历关键字类并将类对象附加到接口(interface)。

问题是这个设备的配置非常分层......例如,如果有很多 ethernet-switching 实例,我不希望 API 用户必须使用:

# Note that each keyword corresponds to a python class that is appended
# to an InterfaceList object behind the scenes...
SET(Interface='ge-0/0/6.0', Family='ethernet-switching', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])
SET(Interface='ge-0/0/7.0', Family='ethernet-switching', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])
SET(Interface='ge-0/0/8.0', Family='ethernet-switching', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])

相反,我希望能够使用:

Family('ethernet-switching')
SET(Interface='ge-0/0/6.0', PortMode='trunk', Vlan=['v100', 'v101', 'v102'])
SET(Interface='ge-0/0/7.0', PortMode='trunk', Vlan=['v100', 'v101', 'v102'])
SET(Interface='ge-0/0/8.0', PortMode='trunk', Vlan=['v100', 'v101', 'v102'])
Family(None)
# API usage continues...

但是,如果不求助于这样的东西,我想不出一种在 python 中编写代码的方法...

f = Family('ethernet-switching')
f.SET(Interface='ge-0/0/6.0', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])
f.SET(Interface='ge-0/0/7.0', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])
f.SET(Interface='ge-0/0/8.0', PortMode='trunk',
Vlan=['v100', 'v101', 'v102'])

在我需要 SET() 从多个类继承之前,这还算不错……例如……

首选 API

# Note: there could be many combinations of classes to inherit from
Family('ethernet-switching')
PortMode('trunk')
SET(Interface='ge-0/0/6.0', Vlan=['v100', 'v101', 'v102'])
SET(Interface='ge-0/0/7.0', Vlan=['v100', 'v101', 'v102'])
PortMode('access')
SET(Interface='ge-0/0/8.0', Vlan=['v100'])
SET(Interface='ge-0/0/9.0', Vlan=['v100'])
Family(None)
PortMode(None)

是否有一种 pythonic 方式来实现我拥有的最后一个 API 示例?如果没有,您能否分享一些关于如何编写类层次结构代码的想法?

最佳答案

这样的事情对你有帮助吗?

from functools import partial
S=partial(SET, Family='ethernet-switching', PortMode='trunk')
S(Interface='ge-0/0/6.0', Vlan=['v100', 'v101', 'v102'])
S(Interface='ge-0/0/7.0', Vlan=['v100', 'v101', 'v102'])
S(Interface='ge-0/0/8.0', Vlan=['v100', 'v101', 'v102'])

关于inheritance - 匿名类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5737728/

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