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.

158 CHAPTER 7 ■ MORE ABSTRACTION<br />

<strong>Python</strong>, all attributes are publicly available, but programmers should still be careful about<br />

accessing an object’s state directly, since they might unwittingly make the state inconsistent<br />

in some way.<br />

Inheritance. One class may be the subclass of one or more other classes. The subclass then<br />

inherits all the methods of the superclasses. You can use more than one superclass, and<br />

this feature can be used <strong>to</strong> compose orthogonal pieces of functionality. A common way of<br />

implementing this is using a core superclass along with one or more mix-in superclasses.<br />

Interfaces and introspection. In general, you don’t want <strong>to</strong> prod an object <strong>to</strong>o deeply. You<br />

rely on polymorphism, and call the methods you need. However, if you want <strong>to</strong> find out<br />

what methods or attributes an object has, there are functions that will do the job for you.<br />

Object-oriented design. There are many opinions about how (or whether!) <strong>to</strong> do objec<strong>to</strong>riented<br />

design. No matter where you stand on the issue, it’s important <strong>to</strong> understand<br />

your problem thoroughly, and <strong>to</strong> create a design that is easy <strong>to</strong> understand.<br />

New Functions in This Chapter<br />

Function<br />

callable(object)<br />

getattr(object, name[, default])<br />

hasattr(object, name)<br />

isinstance(object, class)<br />

issubclass(A, B)<br />

random.choice(sequence)<br />

setattr(object, name, value)<br />

type(object)<br />

Description<br />

Determines if the object is callable (such as a function<br />

or a method)<br />

Gets the value of an attribute, optionally providing<br />

a default<br />

Determines if the object has the given attribute<br />

Determines if the object is an instance of the class<br />

Determines if A is a subclass of B<br />

Chooses a random element from a non-empty sequence<br />

Sets the given attribute of the object <strong>to</strong> value<br />

Returns the type of the object<br />

What Now?<br />

You’ve learned a lot about creating your own objects and how useful that can be. Before diving<br />

headlong in<strong>to</strong> the magic of <strong>Python</strong>’s special methods (Chapter 9), let’s take a breather with a<br />

little chapter about exception handling.

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

Saved successfully!

Ooh no, something went wrong!