Looking for a good introduction to object oriented programming with Python

Roy Smith roy at panix.com
Sun Aug 5 14:39:10 EDT 2012


In article 
<8f1b60a5-0411-4aae-9ee6-0025b493ca2d at m13g2000vbd.googlegroups.com>,
 Jean Dubois <jeandubois314 at gmail.com> wrote:

> Can someone here on this list give a trivial example of what object
> oriented programming is, using only Python?

OOP seems to mean different things to different people.  What OOP means 
to you is usually a strong function of whatever OOP language you learned 
first.  That being said, I think the fundamental, universal, core 
principle of OOP is that an object contains some data, and some code 
that knows how to do something with that data.

So, to give you a simple (but real-life) example, the system I'm working 
in now has User objects.  A user is a pretty complicated class, but 
here's some simple methods from it:

    def __eq__(self, other):
        return isinstance(other, (User, AnonymousUser)) \
          and self.user_id == other.user_id

    def __unicode__(self):
        return self.username

    def __repr__(self):
        return '<User %d: %r>' % (self.user_id, self.username)

This defines a few basic behaviors for User objects.

First, it defines how to tell if something is equal to a given User 
object.  The something must itself be a User (ignore the minor 
complication about AnonymousUser for the moment), and it must have the 
same user_id as this one.  I could easily imagine lots of other possible 
ways two users could be considered equal (same username, for example), 
but we're using user_id.  This means I can write:

   if user1 == user2:
      print "they're the same"

and I don't have to worry about (or even know about) the details.  In 
fact, sometime long after I've written that code, somebody could define 
some new kind of HighSecurityUser which tests for equality by comparing 
the scanned retina images for both of them.  My code wouldn't have to 
change; it would magically just start enforcing retina matching.

Likewise, I can write:

   print user

or

   logger.warning("%r did something interesting", user)

and I don't have to know anything about how to print a User.  The User 
knows how to print itself.



More information about the Python-list mailing list