在ITCL有可能創建一個允許我們可以在tclOO中定義靜態函數嗎?
namespace eval ns {set ::ns::i 0}
::itcl::class clsTest {
set ::ns::i 0 ;
proc i {} {
return [incr ::ns::i]
}
}
clsTest::i
1
是否有tclOO一些這方面的支持類中的一個PROC?
在ITCL有可能創建一個允許我們可以在tclOO中定義靜態函數嗎?
namespace eval ns {set ::ns::i 0}
::itcl::class clsTest {
set ::ns::i 0 ;
proc i {} {
return [incr ::ns::i]
}
}
clsTest::i
1
是否有tclOO一些這方面的支持類中的一個PROC?
類是(大部分)在TclOO普通對象,所以你可以做的事情,如創建的實例方法課本身。這就是self
在類聲明的上下文是,它是一個功能強大的技術:
oo::class create clsTest {
self {
variable i
method i {} {
return [incr i]
}
}
}
之後,那麼你可以做:
clsTest i
# ==> 1
clsTest i
# ==> 2
clsTest i
# ==> 3
注意new
和create
是實際上只是大多數普通的預定義方法(這些方法恰好在C中實現),但你可以添加任何你想要的東西。當然oo::class
繼承自oo::object
。
如果您打算讓類級別的方法也顯示爲可在實例上調用的方法,那麼您只需要欺騙。我不推薦它,但它可能與轉發方法:
oo::class create clsTest {
self { ... }
# This is actually the simplest thing that will work, provided you don't [rename] the class.
# Use the fully-qualified name if the class command isn't global.
forward i clsTest i
}
從tcloo維基在:http://wiki.tcl.tk/21595
proc ::oo::define::classmethod {name {args ""} {body ""}} {
# Create the method on the class if
# the caller gave arguments and body
set argc [llength [info level 0]]
if {$argc == 4} {
uplevel 1 [list self method $name $args $body]
} elseif {$argc == 3} {
return -code error "wrong # args: should be \"[lindex [info level 0] 0] name ?args body?\""
}
# Get the name of the current class
set cls [lindex [info level -1] 1]
# Get its private 「my」 command
set my [info object namespace $cls]::my
# Make the connection by forwarding
tailcall forward $name $my $name
}
oo::class create Foo {
classmethod boo {x} {
puts "This is [self]::boo with argument x=$x"
}
}
Foo create bar
bar boo 42
# --> This is ::Foo::boo with argument x=42
Foo boo 7
# --> This is ::Foo::boo with argument x=7
謝謝,是非常有益的。 – BabyGroot