Oop Tcl中类实例的共享变量

Oop Tcl中类实例的共享变量,oop,static,tcl,Oop,Static,Tcl,在Ruby中,可以为同一类(静态)的实例共享一个变量。也就是说,所有人都看到相同的值,并且可以改变它。它可以节省内存,并具有其他好处。这也可以在Perl、C++等方面实现。在8.6版中,如何实现TCL OO中的相同?谢谢。 < P>因为TclOO是赤裸裸的,需要一点脚本来实现结果。tcllib中的包提供了必要的代码。要使类作用域变量对实例正确可见,需要三个步骤 步骤1:在类中设置一个值: 如果您能够处理一个未设置的变量,那么不需要做太多的工作。有些代码可以,有些不能 oo::class crea

在Ruby中,可以为同一类(静态)的实例共享一个变量。也就是说,所有人都看到相同的值,并且可以改变它。它可以节省内存,并具有其他好处。这也可以在Perl、C++等方面实现。在8.6版中,如何实现TCL OO中的相同?
谢谢。

< P>因为TclOO是赤裸裸的,需要一点脚本来实现结果。tcllib中的包提供了必要的代码。

要使类作用域变量对实例正确可见,需要三个步骤

步骤1:在类中设置一个值: 如果您能够处理一个未设置的变量,那么不需要做太多的工作。有些代码可以,有些不能

oo::class create Example {
    self variable foo
    self method init {} {
        set foo 123
    }
}
Example init
步骤2:为将访问变量的实例定义一些方法 我们举一个例子。请注意,我还必须在这里说
variable
;它与上面的
自变量
的范围不同。(实例与类)

步骤3:将实例变量绑定到构造函数中的类变量 这是棘手的一点

oo::define Example {
    constructor {} {
        # Get the class's own private object namespace, where it keeps its own variables
        set ns [info object namespace [self class]]
        # Link the instance variable to the class variable; 'my eval' uses right context
        # You can rename the variable here; see 'namespace upvar' docs for details
        my eval [list namespace upvar $ns foo foo]
    }
}
有了这三个,我们可以制作一些实例并进行尝试:

set e1 [Example new]
set e2 [Example new]
$e1 bar; # ==> foo is 124
$e1 bar; # ==> foo is 125
$e2 bar; # ==> foo is 126
$e2 bar; # ==> foo is 127
请注意,这是通过实例命名空间中的变量链接到类命名空间中的单个变量来实现的。这个链接是通过
名称空间upvar
完成的,这是一个您以前可能没有使用过的命令。它也可以通过
upvar
命令来完成,尽管这样做效率较低


整合脚本,便于学习 它看起来有点不同,但它做的事情是一样的:

oo::class create Example {
    self {
        variable foo
        method init {} {
            set foo 123
        }
    }
    variable foo
    constructor {} {
        set ns [info object namespace [self class]]
        my eval [list namespace upvar $ns foo foo]
    }
    method bar {} {
        incr foo
        puts "foo is $foo"
    }
}
Example init
set e1 [Example new]
set e2 [Example new]
$e1 bar; # ==> foo is 124
$e1 bar; # ==> foo is 125
$e2 bar; # ==> foo is 126
$e2 bar; # ==> foo is 127

我们可能最终会在TclOO的核心中添加更多的类变量和类方法支持。不过,现在对我来说,这并不是一个很大的优先事项,特别是对于类方法(在相关的类对象上生成self方法可以提供99%的有用效果)。两个问题:1)self{…}行为的文档在哪里?我所看到的只是内省()的特定子命令,2)代码似乎在没有
self{…}
的情况下工作-尽管值显然从1开始,因为没有要调用的
Init
oo::class create Example {
    self {
        variable foo
        method init {} {
            set foo 123
        }
    }
    variable foo
    constructor {} {
        set ns [info object namespace [self class]]
        my eval [list namespace upvar $ns foo foo]
    }
    method bar {} {
        incr foo
        puts "foo is $foo"
    }
}
Example init
set e1 [Example new]
set e2 [Example new]
$e1 bar; # ==> foo is 124
$e1 bar; # ==> foo is 125
$e2 bar; # ==> foo is 126
$e2 bar; # ==> foo is 127