我正在围绕这样的设备配置构建一个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将遍历关键字类并将类对象附加到接口上。
问题是这个设备的配置相当分层.例如,如果有许多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)是否有一种节奏式的方法来实现我的最后一个API示例?如果没有,您能分享一些关于如何编写类的层次结构的想法吗?
发布于 2011-04-20 23:43:47
像这样的东西对你有帮助吗?
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'])发布于 2011-04-21 03:31:30
functools.partial的使用确实是一种优雅的方法,但是如果您想看一种真正的基于隐式上下文的方法,我建议探究decimal.getcontext()、decimal.setcontext()和decimal.localcontext()的实现细节。
文档位于:http://docs.python.org/py3k/library/decimal源代码在:http://hg.python.org/cpython/file/default/Lib/decimal.py#l435
发布于 2011-04-20 23:31:55
这类似于jQuery选择和过滤API,其中它们使用函数链接:
some_set_of_data
.filter(first_criteria)
.filter(second_criteria)他们还引入了end()方法,允许您这样做:
some_set_of_data
.filter(first_criteria)
.filter(second_criteria)
.do_something()
.end()
.do_something_else()注意,在本例中,do_something()是对由first_criteria和second_criteria过滤的数据调用的,而对于仅由first_criteria过滤的数据,则调用do_something_else()。
在Python中复制这种与JavaScript有许多共同点的方法应该是相当容易的。
https://stackoverflow.com/questions/5737728
复制相似问题