Home arrow Python arrow Page 4 - Tuples and Other Python Object Types

How to Break Your Code’s Flexibility - Python

In this conclusion to a four-part article series on Python object types, we will finish our discussion of dictionaries, move on to tuples, and cover related material. This article is excerpted from chapter four of the book Learning Python, Third Edition, written by Mark Lutz (O'Reilly, 2008; ISBN: 0596513984). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Tuples and Other Python Object Types
  2. Tuples
  3. Other Core Types
  4. How to Break Your Code’s Flexibility
  5. And Everything Else
By: O'Reilly Media
Rating: starstarstarstarstar / 4
February 05, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

I’ll have more to say about all these types later in the book, but the last merits a few more words here. The type object allows code to check the types of the objects it uses. In fact, there are at least three ways to do so in a Python script:

  >>> if type(L) ==
type([]):
                           # Type testing, if you must...
           
print 'yes'

  yes
  >>> if type(L) ==
list:
                               # Using the type name
          print 'yes'

  yes
  >>> if isinstance(L, list):     # Object-oriented tests
          print 'yes'

  yes

Now that I’ve shown you all these ways to do type testing, however, I must mention that, as you’ll see later in the book, doing so is almost always the wrong thing to do in a Python program (and often a sign of an ex-C programmer first starting to use Python). By checking for specific types in your code, you effectively break its flexibility—you limit it to working on just one type. Without such tests, your code may be able to work on a whole range of types.

This is related to the idea of polymorphism mentioned earlier, and it stems from Python’s lack of type declarations. As you’ll learn, in Python, we code to object interfaces (operations supported), not to types. Not caring about specific types means that code is automatically applicable to many of them—any object with a compatible interface will work, regardless of its specific type. Although type checking is supported—and even required, in some rare cases—you’ll see that it’s not usually the “Pythonic” way of thinking. In fact, you’ll find that polymorphism is probably the key idea behind using Python well.

User-Defined Classes

We’ll study object-oriented programming in Python—an optional but powerful feature of the language that cuts development time by supporting programming by customization—in depth later in this book. In abstract terms, though, classes define new 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 Python, the following user-defined class might fit the bill:

  >>> class Worker:
        
def __init__(self,
name, pay):
                            # Initialize when created
             
self.name = name       # Self is the new object
             
self.pay = pay
         def lastName(self):
             return
self.name.split()[-1]
                # Split string on blanks
         def
giveRaise(self, percent):
             self.pay *= (1.0 + percent)
                              # Update pay in-place

This class defines a new kind of object that will have name and pay attributes (sometimes called state information), as well as two bits of behavior coded as functions (normally called methods). Calling the class like a function generates instances of our new type, and the class’ methods automatically receive the instance being processed by a given method call (in the self argument):

  >>> bob =
Worker('Bob Smith', 50000)          
# Make two instances
 
>>> sue =
Worker('Sue Jones', 60000)          
# Each has name and pay
 
>>> bob.lastName()                  # Call method: bob is self
 
'Smith'
  >>> sue.lastName()                  # Sue is the self subject
 
'Jones'
  >>> sue.giveRaise(.10)              # Updates sue's pay
 
>>> sue.pay
  66000.0

The implied “self” object is why we call this an object-oriented model: there is always an implied subject in functions within a class. In a sense, though, the class-based type simply builds on and uses core types—a user-definedWorkerobject here, for example, is just a collection of a string and number (nameandpay, respectively), plus functions for processing those two built-in objects.

The larger story of classes is that their inheritance mechanism supports software hierarchies that lend themselves to customization by extension. We extend software by writing new classes, not by changing what already works. You should also know that classes are an optional feature of Python, and simpler built-in types such as lists and dictionaries are often better tools than user-coded classes. This is all well beyond the bounds of our introductory object-type tutorial, though, so for that tale, you’ll have to read on to a later chapter.



 
 
>>> More Python Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: