+ All Categories
Home > Documents > Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is...

Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is...

Date post: 14-Jan-2016
Category:
Upload: edmund-mcbride
View: 214 times
Download: 0 times
Share this document with a friend
Popular Tags:
24
Objects and Classes UC Berkeley Fall 2004, E77 http://jagger.me.berkeley.edu/~ pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative Commons Attribution-ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to Creative
Transcript
Page 1: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Objects and ClassesUC Berkeley

Fall 2004, E77http://jagger.me.berkeley.edu/~pack/e77

Copyright 2005, Andy Packard. This work is licensed under the Creative Commons Attribution-ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to

Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

Page 2: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Classes and Objects

Objects and Classes

User defined classes in Matlab

Methods

Designing a new class–Data–Methods

Constructor

Other methods, including operator overloading

Dispatching and Precedence

Inheritance

An abstract class for get/set/reference/assignment

Page 3: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Classes and Objects

Objects are variables with an identity (the class) and functions (the methods) to operate on them.

Data may look like many different things–given a 3 by 1 column vector. Does it represent

• a date (day/month/year)

• a point in 3-dimensional space– Cartesian coordinates– Cylindrical coordinates– Spherical coordinates

• a quadratic polynomial

• or something else…

And, what functions make sense on the data?

So, classes give data an identity, and associate functions to the identity (don’t allow two dates to be multiplied).

negative, distance between two points, add/subtract if cartesian coordinates are interpreted as components of a geometric vector

subtract two dates, add an integer

add, subtract, multiply, differentiate, integrate, evaluate, etc.

These are the different “methods”

Diff

eren

t ide

ntiti

es

Page 4: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Classes/Objects and Methods in Matlab

Objects are instances of the class

Example: the most common class in Matlab is double. An instance of a double is, for example,

>> M = [2 3;4 5;6 7]

Another common class in Matlab is cell.

>> C = [{M} {’e77’};{pi} {[]};{2} {3}]

is an instance of class cell.

Both classes have the method size and use identical () referencing methods. Only double (+), only cell has {}

>> size(M)

>> size(C)

>> M(1,2)

>> C(1,2)

>> M+M

>> C+C

>> C{3,2}

>> M{3,2}

Page 5: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

User Defined Classes/Objects in Matlab

Associated with a class, an Object is–a structure (ie., struct), with a fixed set (for that class) of fields

• contains the data that constitutes the object

–an internal hidden “tag” which labels the structure as an object of that class, and not just a Matlab struct.

The structure’s fields are not accessible to the user

The user interacts with the object using methods–function m-files (for example) that reside in the method’s folder

for that particular class–Within methods m-files, the fields of the structure are accessible–Certain referencing methods (subsref and subsasgn) allow

the programmer to give user access to the fields if desired. Next lecture for these…

Page 6: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Defining a class in MatlabNeed a class for polynomial objects

–purpose: to distinguish them from ordinary row vectors

Pick a name for the class. This is the “classname”.–example: e177poly

Create a folder of the same name as the class, but beginning with the character “@”. This is referred to as the methods folder.

–example: create folder named @e177poly

Decide on fields, and write the constructor method (an m-file) which creates objects (specific instances of the class)

–The name of the m-file should be the same as the classname.

–The constructor should be placed in the methods folder.

Decide on methods, and write function m-files which implement the methods

Page 7: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

e177poly data fields

Design decision: the struct which contains the data that constitutes an e177poly object will have two fields

–a row vector of coefficients, using the typical Matlab interpretation (ie., the roots command) where the row vector represents the polynomial coefficients, from highest power down to the 0th power, fieldname is coeff

–a single character for the symbol to represent the indeterminate variable of the polynomial, only used in display purposes, fieldname is symbol

With this decision made, the constructor can be written.–The name of the constructor file is e177poly.m–The constructor file goes in the @e177poly folder.

Page 8: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Role of the constructor

The Constructor must–Accept data as input arguments–Create a structure with the appropriate fields–Fill the fields of the structure based on the input arguments–Use the class command to “tag” the structure as an object of

the e177poly class.

If the constructor is called with–no input arguments

• it should create an “empty” or “default” instance.

–an instance of the class as the input argument• it should simply return the object.

Page 9: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Format of the constructor

function h = e177poly(p)

if nargin==0

h.coeff = [];

h.symbol = ’x’;

h = class(h,’e177poly’);

else

if isa(p,’e177poly’)

h = p;

elseif isa(p,’double’)

h.coeff = p;

h.symbol = ’x’;

h = class(h,’e177poly’);

end

end

default instance

Input argument is an object of this class

Usual construction from row vector

Creating the object of class “e77poly” from the structure using class

Create structure from data

Create structure from data

Page 10: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Common methods in the Methods folder

1. The constructor itself

2. the display method, which Matlab automatically calls if there is no semicolon at the end of an expression. Matlab passes the result to the display method.

3. converter methods, which convert the object to a different representation, if appropriate.

4. the get method, to access properties of the object

5. the set method, to change properties of the object

6. Operator overloaded methods, such as plus. The expression A+B is actually plus(A,B). If A and B are objects from the same class, and there is a plus method, it will be called.

Page 11: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Design Decision: Methods for e177poly

Constructor, e177poly

converter and display methods– double, converts a polynomial to a row vector of coefficients– char, converts a polynomial to a formatted string– display, for expressions that result in an e177poly object

Operator overloaded methods– plus(A,B) for A+B– minus(A,B) for A-B– uplus(A) for +A– uminus(A) for -A– mtimes(A,B) for A*B

Overloaded methods– roots, polyval, polyder, polyint

Access methods (get, set), next time @e177poly

e177poly.m

double.m

char.m

display.m

plus.m

minus.m

uplus.m

uminus.m

mtimes.m

roots.m

polyval.m

polyder.m

polyint.m

get.m

set.m

Page 12: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Method Dispatching and Precedence

Suppose A and B are two objects of different class. Consider the expression SomeMethod(A,B)Question: Which method will be called?

– SomeMethod.m in the methods folder of class(A), or …– SomeMethod.m in the methods folder of class(B)?

Answer:– If the objects have equal precedence, then the method from

class(A) (ie., the first argument) will be called.– If the objects have unequal precedence, the method

associated with the object of higher precedence will be called.

Facts:– All user-defined classes have higher precedence than Matlab

built-in classes (like double, char). By default, all user-defined classes are of equal precedence.

– Commands superiorto and inferiorto are used to define precedence among user-defined classes. More next lecture

Page 13: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Dispatching and Precedence

Since e177poly objects have higher precedence than double objects, the sequence of commands

>> A = e177poly([3 -1 4]);

>> C = 2*A % mtimes

>> D = A-5 % minuscall @e177poly/mtimes.m and @e177poly/minus.m methods respectively (each with two arguments).

Let’s write these multi-input argument functions– to handle non-e177poly objects,– knowing at least one argument will be an e177poly object.

Page 14: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Access methods: get and set

The public properties of the object are–Retrieved using get–Modified using set, which can control changes that are allowed

Properties have names to identify them, so a natural syntax is

PropertyValue = get(Object,PropertyName)

set(Object,PropertyName,PropertyValue)

For the e77poly class, let’s make Symbol a public property

–Its value is the single character symbol used to represent the indeterminate variable of the polynomial

–Since the user will be able to control its value, we won’t allow binary operations (like + and *) unless the symbols match.

Page 15: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Writing get is pretty easy

function value = get(p,PropName)

switch PropName

case 'Symbol'

value = p.symbol;

otherwise

error('Unknown property');

end

The convention (we’ll see next week) in Matlab for

value = get(Object)

is to return a struct, whose fieldnames are the public properties. Easy to add this in, using nargin.

Lim

ited

acce

ss

Page 16: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Writing set is a little harder

Why won’t this work?

function set(p,PropName,value)

switch PropName

case ’Symbol’

if isa(value,’char’) & isscalar(value)

p.symbol = value;

else

error(’Invalid Symbol value’);

end

otherwise

error(’Unknown property’);

end

Con

trol

ling

wha

t is

allo

wed

Page 17: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Writing set is a little harder

Without some trickery, the commandset(a,PropName,Value)

will not work as intended. In other words, after executinginitvalue = get(a,PropName);newvalue = some_new_value;set(a,PropName,newvalue)

the result ofisequal(get(a,PropName),newvalue)

is false, and the result ofisequal(get(a,PropName),initvalue)

is true.Why? (week 2/3): variables are passed to functions by value, changing them in the function only changes the function’s copy.

Page 18: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

(recall) Accessing other workspaces

Two built-in Matlab commands to circumvent this by–Allowing assignment of variables in other workspaces–Within a function, giving access to the name of an input

argument variable in the caller’s workspace

Specifically, these two functions are

assignin–copy a variable from the current workspace into a

different workspace, with a new, given name.

inputname–Access the name (in the caller’s workspace) of an input

argument variable.

Page 19: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Example with assignin

>>

>> v1 = [1 -2 3];

>> W = EXAMP1(v1);

>>

function [B] = EXAMP1(A)

assignin(’caller’,’NEWV’,2*A);

B = 3*A;

BASE WORKSPACE

v1: [1 -2 3]

NEWV: [2 -4 6]

W: [3 -6 9]

FUNCTION INSTANCE WS

A: [1 -2 3]

B: [3 -6 9]

function [B] = EXAMP1(A)

assignin(’caller’,’NEWV’,2*A);

B = 3*A;

Page 20: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Example with inputname

>>

>> fred = [2 3];

>> joe = [5 5];

>> W = EXAMP2(fred,joe);

>>

function [C] = EXAMP2(A,B)

D = inputname(1);

E = inputname(2);

C = A + B;

BASE WORKSPACE FUNCTION INSTANCE WS

D: ’fred’

E: ’joe’

C: [7 8]

function [C] = EXAMP2(A,B)

D = inputname(1);

E = inputname(2)

C = A + B;

fred: [2 3]

joe: [5 5]

W: [7 8]

A: [2 3]

B: [5 5]

Page 21: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Example using both

Look at the function incr.m

function incr(a)

assignin(’caller’,inputname(1),a+1);

It increments, without an output argument!

>> var = 7;

>> incr(var);

>> var

var =

8

>>

Page 22: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Fixing set uses this idea

Here is one working version of set

function set(p,PropName,value)

switch PropName

case 'Symbol'

p.symbol = value; % need error check

otherwise

error('Unknown property');

end

assignin(’caller’,inputname(1),p);

Could also pass back an argument, or give user the option to do either…

Page 23: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

A version of set allowing for either…

function pnew = set(p,PropName,value)

switch PropName

case 'Symbol'

p.symbol = value; % need error check

otherwise

error('Unknown property');

end

if nargout==0

assignin(’caller’,inputname(1),p);

else

pnew = p;

end

Page 24: Objects and Classes UC Berkeley Fall 2004, E77 pack/e77 Copyright 2005, Andy Packard. This work is licensed under the Creative.

Nearly finished: Methods for e177poly

• Constructor, e177poly• converter and display methods

– double, converts a polynomial to a row vector of coefficients– char, converts a polynomial to a formatted string– display, for expressions that result in an e177poly object

• Operator overloaded methods– plus(A,B) for A+B– minus(A,B) for A-B– uplus(A) for +A– uminus(A) for -A– mtimes(A,B) for A*B

• Overloaded methods– roots, polyval, polyder, polyint

• Access methods (get, set) @e177poly

e177poly.m

double.m

char.m

display.m

plus.m

minus.m

uplus.m

uminus.m

mtimes.m

roots.m

polyval.m

polyder.m

polyint.m

get.m

set.m


Recommended