6.8 Modules and classes

Modules provide a convenient way to group functions and variables together. Pyxplot’s default functions are grouped into modules such as os and random. New modules can be created by calling the module object, which is a synonym for types.module. Once created, a module is like a dictionary, except that its elements can be accessed both as module[item] and more commonly as module.item. For example:

pyxplot> myFuncs = module()
pyxplot> myFuncs.squared(x) = x**2
pyxplot> myFuncs.cubed(x) = x**3
pyxplot> print myFuncs
module {
  cubed         : cubed(x)=x**3
  squared       : squared(x)=x**2
pyxplot> print myFuncs.squared(4)
pyxplot> print myFuncs[’cubed’](2)

Modules can also serve as class prototypes. If a module is called like a function, the return value is an instance of the module:

pyxplot> oldMan = module()
pyxplot> oldMan.info() = "Barefoot on the ice, $\backslash $n$\backslash $
.......> he staggers back and forth"
pyxplot> hurdyGurdyMan = oldMan()
pyxplot> hurdyGurdyMan.moreInfo() = "With numb fingers $\backslash $n$\backslash $
.......> he plays the best he can."
pyxplot> print hurdyGurdyMan.moreInfo()
With numb fingers $\backslash $nhe plays the best he can.
pyxplot> print hurdyGurdyMan.info()
Barefoot on the ice, $\backslash $nhe staggers back and forth

The module instance inherits all of the functions and variables of its parent object, but may also contain its own additional functions and variables, some of which may supersede those in the parent object if they have the same name. When functions or subroutines of a module instance are called, the special variable self is defined to equal the module instance object. This allows the function to store private data in the module instance, or to call other methods on the instance.

pyxplot> animal = module()
pyxplot> animal.info() = "I am a %s."%self.type
pyxplot> animal.moreInfo() = "My name is %s."%self.name
pyxplot> cat = animal()
pyxplot> cat.type = "cat"
pyxplot> subroutine cat.poke() { print "miaox!" ; }
pyxplot> cat.moreInfo() = "My name is %s."%self.name
pyxplot> tiddles = cat()
pyxplot> tiddles.name = "tiddles"
pyxplot> print tiddles.info()
I am a cat.
pyxplot> print tiddles.moreInfo()
My name is tiddles.
pyxplot> call tiddles.poke()

As this example demonstrates, it is also possible to hierarchically instantiate modules: tiddles is an instance of cat, which is itself an instance of animal.