【发布时间】:2010-12-16 12:59:19
【问题描述】:
我正在为基于 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 版本一样干净的东西吗?
【问题讨论】: