2016-06-21 148 views

回答

2

類是(大部分)在TclOO普通對象,所以你可以做的事情,如創建的實例方法課本身。這就是self在類聲明的上下文是,它是一個功能強大的技術:

oo::class create clsTest { 
    self { 
     variable i 
     method i {} { 
      return [incr i] 
     } 
    } 
} 

之後,那麼你可以做:

clsTest i 
# ==> 1 
clsTest i 
# ==> 2 
clsTest i 
# ==> 3 

注意newcreate實際上只是大多數普通的預定義方法(這些方法恰好在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 
} 
+0

謝謝,是非常有益的。 – BabyGroot

1

從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 
相關問題