12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

How to Break Your Code’s FlexibilityI’ll have more to say about all these types later in the book, but the last merits a fewmore words here. The type object allows code to check the types of the objects ituses. In fact, there are at least three ways to do so in a <strong>Python</strong> script:>>> if type(L) == type([]): # Type testing, if you must...print 'yes'yes>>> if type(L) == list: # Using the type nameprint 'yes'yes>>> if isinstance(L, list): # Object-oriented testsprint 'yes'yesNow that I’ve shown you all these ways to do type testing, however, I must mentionthat, as you’ll see later in the book, doing so is almost always the wrong thing to doin a <strong>Python</strong> program (and often a sign of an ex-C programmer first starting to use<strong>Python</strong>). By checking for specific types in your code, you effectively break its flexibility—youlimit it to working on just one type. Without such tests, your code may beable to work on a whole range of types.This is related to the idea of polymorphism mentioned earlier, and it stems from<strong>Python</strong>’s lack of type declarations. As you’ll learn, in <strong>Python</strong>, we code to object interfaces(operations supported), not to types. Not caring about specific types meansthat code is automatically applicable to many of them—any object with a compatibleinterface will work, regardless of its specific type. Although type checking issupported—and even required, in some rare cases—you’ll see that it’s not usuallythe “<strong>Python</strong>ic” way of thinking. In fact, you’ll find that polymorphism is probablythe key idea behind using <strong>Python</strong> well.User-Defined ClassesWe’ll study object-oriented programming in <strong>Python</strong>—an optional but powerful featureof the language that cuts development time by supporting programming bycustomization—in depth later in this book. In abstract terms, though, classes definenew types of objects that extend the core set, so they merit a passing glance here.Say, for example, that you wish to have a type of object that models employees.Although there is no such specific core type in <strong>Python</strong>, the following user-definedclass might fit the bill:>>> class Worker:def _ _init_ _(self, name, pay):self.name = nameself.pay = pay# Initialize when created# Self is the new object88 | Chapter 4: Introducing <strong>Python</strong> Object Types

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

Saved successfully!

Ooh no, something went wrong!