16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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 <strong>to</strong> worry about the contents of globalName when you use instances<br />

(objects) of the class OpenObject. In fact, you have <strong>to</strong> 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 <strong>to</strong> 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 au<strong>to</strong>matically sets the name of the other. Not<br />

exactly what you want.<br />

Basically, you want <strong>to</strong> treat objects as abstract. When you call a method you don’t want <strong>to</strong><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 <strong>to</strong> 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 <strong>to</strong> 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 s<strong>to</strong>red 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 <strong>to</strong> 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!