Mik*_*ton 5 python inheritance
我正在围绕设备配置构建一个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#
Run Code Online (Sandbox Code Playgroud)
我正在为某些动作(如SET)定义python类,以及为动作的关键字定义类......想法是SET将遍历关键字类并将类对象附加到接口.
问题是这个设备的配置非常分层......例如,如果有很多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'])
Run Code Online (Sandbox Code Playgroud)
相反,我希望能够使用:
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...
Run Code Online (Sandbox Code Playgroud)
但是,我无法想出一种在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'])
Run Code Online (Sandbox Code Playgroud)
在我需要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)
Run Code Online (Sandbox Code Playgroud)
是否有一种pythonic方式来实现我的最后一个API示例?如果没有,你能分享一些关于如何编写类层次结构的想法吗?
Joh*_*ooy 10
这样的事情对你有帮助吗?
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'])
Run Code Online (Sandbox Code Playgroud)