Prev: keyword highlight in text widget
Next: Postgres
From: Donal K. Fellows on 8 Jan 2010 16:41 On 08/01/2010 16:18, Georgios Petasis wrote: > Since classes are objects, is there a way I can add a method (i.e. > cget/configure) for all objects? > > For example, if I use oo::objdefine oo:object method cget {} {}, will > this cget be able to get the value of any variable in any object? That will work. I don't actually recommend it though; all objects means *all*. Better to derive your objects and classes from a class that provides the methods. Since TclOO supports multiple inheritance and mixins, this isn't onerous... Donal.
From: Donal K. Fellows on 9 Jan 2010 03:13
On 08/01/2010 18:24, Georgios Petasis wrote: > I also added the static method from the wiki, for defining > "common"/"class" variables, and the classmethod, for class methods. > The first impression is that they work, but class variables do not seem > to be accessible from class methods. Class variables are just normal instance variables from the perspective of instance methods. Here's how I did them in my paper from Tcl2k9: proc ::oo::Helpers::classvar {name args} { # Get reference to class's namespace set ns [info object namespace [uplevel 1 {self class}]] # Double up the list of varnames set vs [list $name $name] foreach v $args {lappend vs $v $v} # Link the caller's locals to the class's variables tailcall namespace upvar $ns {*}$vs } (The namespace I created that procedure in is magical in that every object has it on its [namespace path], making it an ideal location to put helper commands. It's where the [self] and [next] commands live.) This can be used with class methods as shown in this example: % oo::class create Foo { method foo {} { classvar x puts "This is [self]->foo with variable x=$x" } classmethod bar {y} { variable x incr x $y } } ::Foo % Foo create a ::a % Foo create b ::b % a bar 1 1 % b bar 2 3 % a foo This is ::a->foo with variable x=3 % b foo This is ::b->foo with variable x=3 Note that I'm not using any variable declarations, just the [variable] and [classvar] commands. A [self variable] declaration would have worked for the class variables, but it's probably better for some future revision of TclOO to provide better support, but only once some more experience has taught us what we want to do. Donal. |