开发者

Static function inheritance in [incr Tcl]

Inheritance in incr Tcl doesn't work as expected. Consider the code below.

package require Itcl

::itcl::class Base \
{
public {
    proc function { } { puts "==== Base::function" }
}
}

::itcl::class Derived { inherit Base }

Base::function
Derived::function    ;# FAILS

The last line fails, so Base::function is not inherited at Derived, though Derived inherits fr开发者_如何学Com Base.

Am I doing something wrong, or incr Tcl is designed to behave so?


Reading the docs I don't think that procs in an itcl class work the way you think they ought to:

proc name ?args? ?body? Declares a proc called name. A proc is an ordinary procedure within the class namespace. Unlike a method, a proc is invoked without referring to a specific object. When the proc body is executed, it will have automatic access only to common data members. If the args list is specified, it establishes the usage information for this proc. The body command can be used to redefine the proc body, but the args list must match this specification. Within the body of another class method or proc, a proc can be invoked like any other command-simply by using its name. In any other namespace context, the proc is invoked using a qualified name like "className::proc". Procs in a base class that are redefined in the current class, or hidden by another base class, can also be accessed via their qualified name.

My reading of this is that the proc is associated with it's class, it can be referred to in the derived class but it isn't defined in it. For example the following works:

package require Itcl

::itcl::class Base {
    public {
        proc function { } { puts "==== Base::function" }
    }
}

::itcl::class Derived { 
inherit Base 
    public {

        proc function { } { 
            puts "==== Derived::function"
            return [Base::function] 
        }
    }
}

Base::function
Derived::function    ;# FAILS


The proc you defined Base::function is (more or less) a regular proc in the namespace Base. When you inherit in Itcl, you just inherit methods, you don't inherit procs. In a related note, you cannot call the proc function from an instance of Base, you have to call it like any regular proc.

itcl::class Base {
  public {
    proc function { } { puts "==== Base::function" }
  }
  public method test {} {
    $this function
  }
  public method test2 {} {
    function
  }
}

Base bb
bb test   ;# yields error: bad option "function"
bb test2  ;# works as expected
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜