Disclosure: I wrote TclOO (with a lot of help from others in the design and testing).
Simple Beginning
TclOO allows very simple use, but can get enormously more complex when you start using a large fraction of its features. Here's a quick sample:
# Make a class
oo::class create Example {
variable x ;# Not the same as [variable] in a namespace!
constructor {} {
set x 1
}
method bar {} {
return [incr x]
}
}
Example create foo ;# Make an instance
puts [foo bar] ;# Call the instance to get 2
puts [foo bar] ;# Call the instance to get 3
puts [foo bar] ;# Call the instance to get 4
foo destroy ;# Kill the instance
Writing a class is pretty simple, and the above gives you enough to do a lot. There are a few basic features that aren't listed: superclass
lets you name the parent class of a class, it defaults to oo::object
which is the class of all objects; forward
lets you dispatch a method call to another command, a sort-of easy delegation; destructor
lets you write something that is called when the object goes away; doing Example new
would make an object without naming it, the name of the created object is the result of calling that; the name of the current object is the result of calling self
inside a method.
Constructors and methods can take arguments just like the basic Tcl proc
command. Destructors can't.
More Complex
Objects can be rename
d, just like any other Tcl command, and there is a whole slew of introspection available for them underneath info object
and info class
. You can attach special per-object behavior to any object with oo::objdefine
. Every object has a private namespace which you can use to store state in (that's where the x
variable in the above example lives).
Methods are not exported by default if their name doesn't start with a lower-case letter (strictly, it depends on whether it matches the glob pattern “[a-z]*
”). You can change this if you prefer.
Classes are themselves objects (instances of oo::class
) which is why they are created by calling oo::class create
; their constructor passes the script you provide to the command oo::define
, which is responsible for defining the behavior of classes. The create
and new
methods are just that: methods on classes that make instances of those classes (named/unnamed respectively).
You can use multiple inheritance. And mixins. And filters. And add a dispatch handler to deal with attempts to call an unknown method.
You can subclass oo::class
itself to let you define new ways of making and managing objects.
You can change the class of any object at runtime (except for oo::object
and oo::class
; they're specially locked for reasons of sanity).
…
Yes, I'm the author of TclOO but I'm still exploring what my creation can do. I've tried very hard to ensure that will do virtually anything you ask of it.