Python
  Home arrow Python arrow Page 4 - Tuples and Other Python Object Types
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

Tuples and Other Python Object Types
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2009-02-05


    Table of Contents:
  • Tuples and Other Python Object Types
  • Tuples
  • Other Core Types
  • How to Break Your Code’s Flexibility
  • And Everything Else

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Tuples and Other Python Object Types - How to Break Your Code’s Flexibility
    ( Page 4 of 5 )

    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 subjec t
     
    'Jones '
      >>> sue.giveRaise(.10)              # Updates sue's pa y
     
    >>> 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-defined Worker object here, for example, is just a collection of a string and number ( name and pay , respectively), plus functions for processing those two built-in objects.

    The larger story of classes is that their inheritance mechanism supports software hier archies 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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek