我正在为基于 XML 的 Web 服务构建 Smalltalk API。XML 服务是如此的有规律,以至于与其手动编写方法,我想我只需重写#doesNotUnderstand:
以通过 动态添加方法MyApi class>>compile:
,然后在工作区中调用所有方法一次,然后删除 DNU 并拥有我的漂亮 API。
这很好用,但是将一根巨大的字符串传递#compile:
给我感觉真的很不对;在 Python 和其他语言中,我可以将一个经过语法检查的 lambda 附加到一个类,以更安全的方式实现类似的效果。例如:
def himaker(name):
def hello(self, times):
for x in xrange(times):
print "Hi, %s!" % name
return hello
class C(object): pass
C.bob = himaker('Bob')
C.jerry = himaker('Jerry')
a = C()
a.bob(5)
相对
SomeObject>>addHello: name
| source methodName |
methodName := 'sayHello', name, 'Times:'.
source := String streamContents: [ :s |
s nextPutAll: methodName, ' count'.
s nextPut: Character cr.
s nextPut: Character tab.
s nextPutAll: 'count timesRepeat: [ Transcript show: ''Hi, ', name, '!'' ].' ]
SomeObject class compile: source
肯定有像 Python 版本一样干净的东西吗?