Version 2 of TclOO Tutorial

Updated 2011-01-12 14:46:03 by jblz

[extracted from this c.l.t posting ]

For very basic usage, here's this. It assumes you know a bit about OO systems in general.

Declare a class like this:

  oo::class create MyExampleClass { 
      constructor {args} {# like [proc] 
          # Do something with the args... 
      } 
      # Public methods begin with lower-case letters 
      method foo {bar boo} {# like [proc] 
          puts "bar=$bar, boo=$boo" 
      } 
      destructor {# No arguments 
          # Clean up here if necessary 
      } 
  }

Use that class/object like this:

  MyExampleClass create exampleObj someArgumentToConstructor... 
  exampleObj foo 1 2;    # prints 'bar=1, boo=2' 
  exampleObj destroy;    # wipes the object out 
  set obj [MyExampleClass new];  # 'Unnamed' object 
  $obj foo 3 4;          # prints 'bar=3, boo=4' 
  $obj destroy 

Every object (i.e., every instance) has its own arbitrarily-named namespace that is not shared with anything else. It is the current namespace when a method (or constructor or destructor) is executing. Store state in there, perhaps like this:

  oo::class create Example2 { 
      constructor x { 
          variable X $x 
      } 
      method addToX y { 
          variable X 
          set X [expr {$X + $y}] 
          return 
      } 
      destructor { 
          variable X 
          puts "X is $X" 
      } 
  } 
  Example2 create eg 3 
  eg addToX 5 
  eg addToX 2 
  eg destroy;             # Prints 'X is 10' 

Introspection is done by info class, info object and (within methods only) self. For example, the name of an object's private namespace is given by info object namespace $obj. By itself, self returns the name of the currently-executing object. See the documentation for details.

Private methods are methods whose names don't begin with a lower-case letter. They can be invoked on an object by using my instead of the object name, like this:

  ... 
  method ThePrivateMethod ... ... 
  method aPublicMethod ... { 
      puts "before the private call" 
      my ThePrivateMethod ... 
      puts "after the private call" 
  } 
  ... 

The my command is always located in the object's private namespace. This makes it ideal (with a very little trickery) for handling callbacks like traces and events.

Expert stuff: classes are objects themselves (instances of oo::class) which is why the syntax for making a class is so much like the syntax for making a named object. Because it's exactly the same. This is a deep rabbit-hole, but I'll stop writing this up here. :-)


jblz Other helpful resources include: The original TclOO TIP , and it's companion . There is also quite a bit of general purpose TclOO code in the libraries of wub , if one is looking for examples of TclOO in action.