如何为当前类的任意对象调用itcl :: scope?

时间:2012-01-07 22:57:31

标签: oop scope tcl incr-tcl

itcl::scope返回$this指定成员变量的全名。

如何为同一个班级的另一个对象(不是$this)调用itcl::scope

这是一种解决方法。

itcl::class dummy {
    variable m_data

    method function { other } {
        if { [itcl::is object -class dummy $other] } {
            error "Invalid argument."
        }

        set name "@itcl $other [$other info variable m_data -name]"
        # OR
        set name [lreplace [itcl::scope m_data] 1 1 $other]

        puts "==== this is the name of m_data of of object $other: $name"
    }
}

但这很丑陋,说得客气一点。

我认为$other info variable m_data -name应该返回我想要的内容,但它只是省略了对象的上下文。

1 个答案:

答案 0 :(得分:0)

获取这些信息并不是一个好方法,制作一个信息也不是一件好事。通常最好将对象的变量视为该对象实现的一部分,而不是其对象的一部分。因此,外部代码不应该像那样在内部徘徊;如果对象外部的某些东西(包括该类的其他成员)访问变量很重要,请编写一个方法来返回对变量的引用(使用itcl::scope生成)。

itcl::class dummy {
    variable m_data

    protected method dataRef {} { itcl::scope m_data }

    method function { other } {
        if { [itcl::is object -class dummy $other] } {
            error "Invalid argument."
        }

        set name [$other dataRef]

        puts "==== this is the name of m_data of of object $other: $name"
    }
}