请教perl中dispatch方法的实现方法?
时间:2010-11-13
来源:互联网
最近在看beginning python ,看到如下代码
class Handler:
"""
An object that handles method calls from the Parser.
The Parser will call the start() and end() methods at the
beginning of each block, with the proper block name as a
parameter. The sub() method will be used in regular expression
substitution. When called with a name such as 'emphasis', it will
return a proper substitution function.
"""
def callback(self, prefix, name, *args):
method = getattr(self, prefix+name, None)
if callable(method): return method(*args)
def start(self, name):
self.callback('start_', name)
def end(self, name):
self.callback('end_', name)
def sub(self, name):
def substitution(match):
result = self.callback('sub_', name, match)
if result is None: match.group(0)
return result
return substitution
该代码中实现了所有名字为start_,end_,sub_开头的函数的抽象,比如start_html,start_heading,start_paragraph和end_html,end_heading.
我自己google了一下,类似的代码出现在imtermediate perl 和modern perl中,
my %start=
(
$html=>\&start_html,
$heading=>\&start_head,
...
}
my %end=
(...)
start_html{}
start_heading{}
使用的时候使用
for $element(@element){
$start{$element}->();
...
}
我不知道有没有更接近于上述python中代码的实现,希望大家能够告诉我一下,谢谢!
class Handler:
"""
An object that handles method calls from the Parser.
The Parser will call the start() and end() methods at the
beginning of each block, with the proper block name as a
parameter. The sub() method will be used in regular expression
substitution. When called with a name such as 'emphasis', it will
return a proper substitution function.
"""
def callback(self, prefix, name, *args):
method = getattr(self, prefix+name, None)
if callable(method): return method(*args)
def start(self, name):
self.callback('start_', name)
def end(self, name):
self.callback('end_', name)
def sub(self, name):
def substitution(match):
result = self.callback('sub_', name, match)
if result is None: match.group(0)
return result
return substitution
该代码中实现了所有名字为start_,end_,sub_开头的函数的抽象,比如start_html,start_heading,start_paragraph和end_html,end_heading.
我自己google了一下,类似的代码出现在imtermediate perl 和modern perl中,
my %start=
(
$html=>\&start_html,
$heading=>\&start_head,
...
}
my %end=
(...)
start_html{}
start_heading{}
使用的时候使用
for $element(@element){
$start{$element}->();
...
}
我不知道有没有更接近于上述python中代码的实现,希望大家能够告诉我一下,谢谢!
作者: littlelittledog 发布时间: 2010-11-13
本帖最后由 zhlong8 于 2010-11-13 20:07 编辑
如果你理解 perl 的 OO 或者看完你上面说的 imtermediate perl 这根本就不是个问题。基本上用 perl 的语法把你上面的 Handle 照抄下就行,能用而且足够像。
楼主在 beginning python 难道楼主正在 python perl 同时入门中?
如果你理解 perl 的 OO 或者看完你上面说的 imtermediate perl 这根本就不是个问题。基本上用 perl 的语法把你上面的 Handle 照抄下就行,能用而且足够像。
楼主在 beginning python 难道楼主正在 python perl 同时入门中?
作者: zhlong8 发布时间: 2010-11-13
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28