Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

oop - 如何从Tcl的超类内部访问派生类成员变量?(How does one access a derived classes member variables from within the superclass in Tcl?)

Code:

(码:)

package require TclOO

oo::class create Supe {
    variable cape boots

    constructor {} {
        puts -nonewline "Supe: "
        puts [info class variables [self class]]
    }
}

oo::class create Clark {
    superclass Supe

    variable glasses suit

    constructor {} {
        puts -nonewline "Clark: "
        puts [info class variables [self class]]
        next
    }
}

set hero [Clark new]

Output:

(输出:)

Clark: glasses suit
Supe: cape boots

Is it possible to get a list of Clark's member variables from within Supe's constructor without passing them into Supe as an argument?

(是否可以从Supe的构造函数中获取Clark的成员变量列表,而无需将其作为参数传递给Supe?)

Ultimately, the goal is to dynamically set derived class variables from a dict argument:

(最终,目标是从dict参数动态设置派生类变量:)

foreach {varName} [info class variables [self class]] {
    variable $varName [dict get $args $varName]
}

If the above code can be used in the superclass constructor, it would avoid putting it in each derived class constructor.

(如果以上代码可在超类构造函数中使用,则应避免将其放在每个派生类构造函数中。)

  ask by Brad Waite translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get the name of the object with self object , or just self .

(您可以使用self objectself来获取对象的名称。)

You can then get the class of the object with info object class .

(然后,您可以使用info object class 。)

And finally, you can get the member variables of a class with info class variables .

(最后,您可以获得带有info class variables的类的成员info class variables 。)

Putting it all together results in:

(将所有内容放在一起会导致:)

[info class variables [info object class [self]]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...