使用构造函数中的方法扩展 Itcl 对象

Extend Itcl objects with methods inside the constructor

在 Itcl 中是否可以使用构造函数中的方法动态扩展 class?

我有一些动态生成的函数...

它们看起来像这样:

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 对象会更好。

一些背景信息:

这用于生成一种抽象语言,用户可以通过编写这些属性而无需任何其他关键字来轻松添加这些属性。在这里使用函数提供了很多我不想错过的优势。

在 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...

看起来对我有用…