Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

4.2 Accessor Methods

When we have an object in our program, we may wish to learn something about the state of that object. To ask for information about an object you must call an accessor method. Accessor methods return information about the state of an object.

Example 4.4 To learn the heading of the turtle we might call the heading method.

1 i m p o r t turtle

2

3 t = turtle.Turtle ()

4

5 p r i n t (t.heading ())

Calling the heading method on the turtle means writing t followed by a dot (i.e. a period) followed by the name of the method, in this case heading. The accessor method, heading, returns some information about the object, but does not change the object. Accessor methods do not change the object. They only access the state of the object.

Practice 4.5 Is the forward method an accessor method? What about the xcor method? You might have to consult Chap. 13 to figure this out.

4.3 Mutator Methods

Mutator methods, as the name suggests, change or mutate the state of the object. Sect. 3.5 introduced the mutability of lists. Mutator methods are called the same as accessor methods. Where an accessor method usually gives you information back, a mutator method may require you to provide some information to the object.

Example 4.5 Here are some calls to mutator methods.

turtle.right (90)

turtle.begin_fill ()

turtle.penup ()

One misconception about object-oriented programming is that assigning one reference to another creates two separate objects. This is not the case as is demonstrated by the following code. This isn't a problem if the object doesn't change. However, when the object may be mutated it is important to know that the object is changing and this means that it changes for all references that point at the object.

Example 4.6 Here is an example of one turtle with two different references to it. Both t and r refer the the same turtle.

1 t = Turtle ()

2 t.forward (50)

3

4 r = t

5

6 r.left (90)

7 r.forward (100)

8

9 t.left (90)

10 t.forward (50)

In Example 4.6 more than one reference points to the same Turtle object as depicted in Fig. 4.3. Writing r = t does not create a second Turtle. It only points both references to the same Turtle object. This is clear from Example 4.6 when one Turtle seems to pick up where the other left off. In fact, they are the same turtle.

Practice 4.6 How would you create a second Turtle object for r if that's really what you wanted?

Fig. 4.3 Two references to one object

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel