在Itcl中是否有可能用构造函数中的方法动态扩展类?
我有一些动态生成的函数.
它们看起来就像这样:
proc attributeFunction fname {
set res "proc $fname args {
#set a attribute list in the class
}"
uplevel 1 $res
}现在我有了一个文件,它有一个可能的属性列表:
attributeFunction ::func1
attributeFunction ::func2
attributeFunction ::func3
...这个文件有来源。但到目前为止,我还在增加全局函数。将这些函数作为方法添加到Itcl对象中会更好。
一些背景资料:
这用于生成一种抽象语言,用户可以通过编写这些属性轻松地添加这些属性,而无需任何其他关键字。函数的使用在这里提供了许多我不想错过的优点。
发布于 2015-01-17 21:04:20
在Itcl 3中,您所能做的就是重新定义一个现有方法(使用itcl::body命令)。不能在构造函数中创建新方法。
您可以在Itcl 4中这样做,因为它构建在TclOO (一个完全动态的OO核心)的基础上。您需要底层的TclOO工具来完成这个任务,但是您调用的命令如下所示:
::oo::objdefine [self] method myMethodName {someargument} {
puts "in the method we can do what we want..."
}下面是一个更完整的例子:
% package require itcl
4.0.2
% itcl::class Foo {
constructor {} {
::oo::objdefine [self] method myMethodName {someargument} {
puts "in the method we can do what we want..."
}
}
}
% Foo abc
abc
% abc myMethodName x
in the method we can do what we want...在我看来这很管用,…
https://stackoverflow.com/questions/27985124
复制相似问题