- 论坛徽章:
- 0
|
最近在看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中代码的实现,希望大家能够告诉我一下,谢谢! |
|