Newbie with some doubts.

Bruno Desthuilliers bdesth.quelquechose at
Mon Jan 9 08:50:13 EST 2006

Edgar A. Rodriguez a écrit :
> Hi everybody,
> Im newbie to Python (I found it three weeks ago) , in fact Im newbie to
> programming. I'm being reading and training with the language, but I
> still wondering about what Classes are used to. 

A class is the definition of a type of object, and let you add your own 
object types to the language.

In fact, as soon as you're programming in Python, you are using classes 
and objects, even if you're not aware of it. *Everything* in Python is 
an object (ie: an 'instance' of a class). The string "foo" is an 
instance of class string, the number 42 is an instance of class int, 
etc. Even functions are objects (instances of class function, yes), so 
you can access (and modify) the properties of a function:

def fun():
   "a dummy function"
   return "foo"

=>"a dummy function"
=> <type 'function'>

> Could you please give
> me some examples??

Let's go with the good ole (and very dumb) example of a shapes drawing 

# The procedural (ie: no classes) version:

def draw_line(from, to):
   # code here

def draw_square(origin, width):
   # code here

def draw_circle(center, radius):
   # code here

shapes = [
   {'type': 'square',
    'origin' : (10,10),
    'width' : 20},
   {'type': 'circle',
    'center': (40, 40),
    'radius': 10},
   {'type', 'line',
    'origin' : (42,42)
    'end' : (48,84)}

def draw_shape(shapes):
   for s in shapes:
     if s['type'] == 'line':
       draw_line(s['origin'], s['end'])
     elif s['type'] == 'square':
       draw_square(s['origin'], s['width'])
     elif s['type'] == 'circle':
       draw_circle(s['center'], s['radius'])
       raise TypeError, "item %s is not a valid shape" % s

# the ObjectOriented version :

class Line(object):
   def __init__(self, origin, end):
     self.origin = origin
     self.end = end

   def draw(self):
     # code here

class Circle(object):
   def __init__(self, center, radius): = center
     self.radius = radius

   def draw(self):
     # code here

class Square(object):
   def __init__(self, origin, width):
     self.origin = origin
     self.width = width

   def draw(self):
     # code here

shapes = [
   Square((10,10), 20),
   Circle((40, 40),10),
   Line((42,42), (48,84)),

def draw_shapes(shapes):
   for s in shapes:

Now try to add to both versions a new type of shape, 'rect', with 
origin, width and height. In the first case, you'll need to modify the 
draw_shapes() function. In the second case, since each shape type know 
how to draw itself (this is called 'encapsulation'), you'll only have to 
define the Rect class.

The example being a small and dumb example, the advantage may not be 
that obvious, but think of what this would mean for a full-featured 
shape drawing program. And there is of course *much* more than this in 


More information about the Python-list mailing list