Next: Indexing Objects, Previous: Creating a Class, Up: Object Oriented Programming [Contents][Index].
Display the contents of an object. If a is an object of the
class
"myclass", then
display is called in a case like
myclass (…)
where Octave is required to display the contents of a variable of the
type
"myclass".
See also: class, subsref, subsasgn.
An example of a display method for the polynomial class might be
function display (p) a = p.poly; first = true; fprintf ("%s =", inputname (1)); for i = 1 : length (a); if (a(i) != 0) if (first) first = false; elseif (a(i) > 0) fprintf (" +"); endif if (a(i) < 0) fprintf (" -"); endif if (i == 1) fprintf (" %g", abs (a(i))); elseif (abs(a(i)) != 1) fprintf (" %g *", abs (a(i))); endif if (i > 1) fprintf (" X"); endif if (i > 2) fprintf (" ^ %d", i - 1); endif endif endfor if (first) fprintf (" 0"); endif fprintf ("\n"); endfunction:
function s = get (p, f) if (nargin == 1) s.poly = p.poly; elseif (nargin == 2) if (ischar (f)) switch (f) case "poly" s = p.poly; otherwise error ("get: invalid property %s", f); endswitch else error ("get: expecting the property to be a string"); endif else print_usage (); endif endfunction
Similarly, the
set method should taken as its first argument an
object to modify, and then take property/value pairs to be modified.
function s = set (p, varargin) s = p; if (length (varargin) < 2 || rem (length (varargin), 2) != 0) error ("set: expecting property/value pairs"); endif while (length (varargin) > 1) prop = varargin{1}; val = varargin{2}; varargin(1:2) = []; if (ischar (prop) && strcmp (prop, "poly")) if (isvector (val) && isreal (val)) s.poly = val(:).'; else error ("set: expecting the value to be a real vector"); endif else error ("set: invalid property of polynomial class"); endif endwhile endfunction
Note that as Octave does not implement pass by reference, than the
modified object is the return value of the
set method and it
must be called like
p = set (p, "a", [1, 0, 0, 0, 1]);]