TclOO:获取创建对象的 class 的名称

TclOO : Get the name of class where the object was created

我有两个 classes :

oo::class create p1 {
    constructor {} {
        # Here I would like to know where the object was created.
        # Inside second class or other
    }
}

oo::class create p2 {
    constructor {} {

    }
}

oo::define p2 {
    method testSecond {} {
        set obj [p1 new]
    }
}
set obj1 [p1 new]
set obj2 [p2 new]

$obj2 testSecond

我试过了: puts "Infoname Class= [info object class [self]]"p1 class 构造函数中。但是每次我都有 Infoname Class= ::p1.

对象是全局创建的,因此它们不存储有关创建者的信息。

如果你坚持,可以在构造函数中通过uplevel查看:

oo::class create p1 {
    constructor {} {
        set ns [uplevel 1 [list namespace current]]
        if {[info object isa object $ns]} {
            puts "Infoname Class= [info object class $ns]"
        } else {
            puts Other
        }
    }
}

但那是非常脆弱的。我不会推荐它。