functional-programmingtclitcl

Extend Itcl objects with methods inside the constructor


Is there a possibility in Itcl to extend a class dynamically with methods inside the constructor?

I have some functions which are generated dynamically...

They look somehow like this:

proc attributeFunction fname {
    set res "proc $fname args {
        #set a attribute list in the class  
    }"
    uplevel 1 $res
}

Now I have a file which has a list of possible attributes:

attributeFunction ::func1
attributeFunction ::func2
attributeFunction ::func3 
...

This file gets sourced. But until now I am adding global functions. It would be way nicer to add these functions as methods to an Itcl object.

A little background information:

This is used to generate an abstract language where the user can easily add these attributes by writing them without any other keyword. The use of functions here offers a lot of advantages I do not want to miss.


Solution

  • In Itcl 3, all you can do is redefine an existing method (using the itcl::body command). You can't create new methods in the constructor.

    You can do this in Itcl 4, because is built on the foundation of TclOO (a fully dynamic OO core). You'll need the underlying TclOO facilities to do this, but the command you call is something like this:

    ::oo::objdefine [self] method myMethodName {someargument} {
        puts "in the method we can do what we want..."
    }
    

    Here's a more complete example:

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

    Looks like it works to me…