Newbie with some doubts.
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
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"
fun.___doc__
=>"a dummy function"
fun.__class__
=> <type 'function'>
> Could you please give
> me some examples??
Let's go with the good ole (and very dumb) example of a shapes drawing
program.
# 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'])
else:
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):
self.center = 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:
s.draw()
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
OOP...
HTH
More information about the Python-list
mailing list