oo::objdefine $obj method name args body gives one object its own method. Object methods are found before class methods, so calling next inside it runs the class version. Calling next twice runs it twice, which is why bump jumps from 1 to 3.
Tcl Expert · Lesson 1 · On the house
TclOO metaprogramming: objdefine, next, metaclasses and mixins
Change one object without touching its class, chain to the method you replaced, customise creation with a metaclass, and wrap methods with a mixin. Lesson 1 is free — on the house.
Lessons · Tcl Expert · Lesson 1 of 10 · On the house
TclOO metaprogramming: objdefine, next, metaclasses and mixins
Change one object without touching its class, chain to the method you replaced, customise creation with a metaclass, and wrap methods with a mixin.

info object class $obj returns the class of any object, and info class instances Cls lists every live instance. Classes are objects too, so info object class Point returns its metaclass.
A metaclass is a class with superclass oo::class. Its create method runs whenever a class built from it makes an instance, so it can log, validate or register objects and then call next $name {*}$args to do the real work.
oo::define Cls method ... adds a method to a class that already has live instances, and they pick it up at once, because method lookup happens at call time.
Method names that start with a lower-case letter are exported (public) by default. info object methods $obj -all lists every public method the object can call, including the built-in destroy.
oo::objdefine $obj mixin Cls puts the mixin class in front of the object's own class. A mixin method with the same name runs first, and next passes control to the original, which makes mixins the standard way to add logging, caching or checks around existing methods.
tcloo metaprogramming
oo::class create Counter {
variable n
constructor {} { set n 0 }
method bump {} { incr n }
}
set c [Counter new]
$c bump
oo::objdefine $c method bump {} { next; next }
puts [$c bump]
puts [info object class $c]
puts [llength [info class instances Counter]]
oo::class create Meta {
superclass oo::class
method create {name args} { puts "making $name"; next $name {*}$args }
}
Meta create Point { variable x; constructor {v} { set x $v }; method x {} { return $x } }
Point create p 7
puts [p x]
puts [info object class Point]
oo::define Point method double {} { expr {[my x] * 2} }
puts [p double]
puts [lsort [info object methods p -all]]
oo::class create Logged {
method x {} { set v [next]; puts "x -> $v"; return $v }
}
oo::objdefine p mixin Logged
p x
Quiz
Quiz
Quiz
Quiz
Check
Match the still for: TclOO metaprogramming: objdefine, next, metaclasses and mixins.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.