2016-06-21 22 views
0

In itcl war es möglich, eine proc innerhalb einer Klasse zu erstellen, dieKönnen wir statische Funktionen in tcOO definieren?

namespace eval ns {set ::ns::i 0} 

::itcl::class clsTest { 
    set ::ns::i 0 ; 
    proc i {} { 
     return [incr ::ns::i] 
    } 
} 

clsTest::i 
1 

erlaubt Gibt es eine Unterstützung für diese in tclOO?

Antwort

2

Klassen sind (meistens) gewöhnliche Gegenstände in TclOO, so dass Sie Dinge wie das Erstellen Instanzmethoden auf das tun können, Klasse selbst. Das ist, was self in einer Klasse-Deklarationskontext ist für, und es ist eine leistungsstarke Technik:

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

Danach können Sie dann tun:

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

Beachten Sie, dass new und create sind tatsächlich nur meistens - vordefinierte Standardmethoden (die zufällig in C implementiert sind), aber Sie können so ziemlich alles hinzufügen, was Sie wollen. Und natürlich erbt oo::class von oo::object.

Sie brauchen wirklich nur Tricks, wenn Sie die Methoden auf Klassenebene auch als auf Instanzen aufrufbare Methoden erscheinen lassen wollen. Ich empfehle es nicht wirklich, aber es ist mit weitergeleiteten Methoden möglich:

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

Danke, war sehr hilfreich. – BabyGroot

1

Von tcloo Wiki unter: 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 
Verwandte Themen