04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

144 CHAPTER 7 ■ MORE ABSTRACTION<br />

'Sir Lancelot'<br />

This means that you have to worry about the contents of globalName when you use instances<br />

(objects) of the class OpenObject. In fact, you have to make sure that nobody changes it:<br />

>>> globalName = 'Sir Gumby'<br />

>>> o.getName()<br />

'Sir Gumby'<br />

Things get even more problematic if you try to create more than one OpenObject because<br />

they will all be messing with the same variable:<br />

>>> o1 = OpenObject()<br />

>>> o2 = OpenObject()<br />

>>> o1.setName('Robin Hood')<br />

>>> o2.getName()<br />

'Robin Hood'<br />

As you can see, setting the name of one automatically sets the name of the other. Not<br />

exactly what you want.<br />

Basically, you want to treat objects as abstract. When you call a method you don’t want to<br />

worry about anything else, such as not disturbing global variables. So how can you “encapsulate”<br />

the name within the object? No problem. You make it an attribute. Attributes are variables<br />

that are a part of the object, just like methods; actually methods are almost like attributes<br />

bound to functions. (You’ll see an important difference between methods and functions in the<br />

section “Attributes, Functions, and Methods,” later in this chapter.)<br />

If you rewrite the class to use an attribute instead of a global variable, and you rename it<br />

ClosedObject, it works like this:<br />

>>> c = ClosedObject()<br />

>>> c.setName('Sir Lancelot')<br />

>>> c.getName()<br />

'Sir Lancelot'<br />

So far, so good. But for all you know, this could still be stored in a global variable. Let’s<br />

make another object:<br />

>>> r = ClosedObject()<br />

>>> r.setName('Sir Robin')<br />

r.getName()<br />

'Sir Robin'<br />

Here we can see that the new object has its name set properly. Well, we expected that. But<br />

what has happened to the first object now?<br />

>>> c.getName()<br />

'Sir Lancelot'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!