tutorial example

Colin J. Williams cjw at sympatico.ca
Sat Nov 12 16:50:44 CET 2005


Ruben Charles wrote:
> That is the diference between a method and a function.
> A method do something and a function return something.
> 
This is not quite correct. The difference between a method and a 
function is that the method is associated with a type or class object, a 
function is not.

A method can be bound to a particular instance of an object or it can be 
unbound.  In the latter case the first argument of the method call 
should be an instance of the type or class object.  However, there is no 
builtin check to ensure that the first argument is in fact an instance.

Please see the little example below.

Colin W.
# areaToy.py

class Point(object):
   def __init__(self, x, y):
     self.x= x
     self.y= y

class Area(object):
   def __init__(self, *pts):
     ''' pts is a list of points describing the enclosing polygon,
     in clockwise order, instances of Point. '''
     self.pts= pts[0]

   def size(self):
     nPts= len(self.pts)
     if nPts < 3:
       return 0
     elif nPts == 3:
       return 0.5               # replace this with triangle area calc
     else:
       pts= self.pts
       return Area(pts[0:2] + [pts[-1]]).size() +            \
              Area(pts[1:]).size()

pts= [Point(*pt) for pt in [(0, 1), (1, 1), (1, 0), (0, 0)]]
area= Area(pts)
size= area.size()
print 'points:', pts
print 'size:', size
print 'Area.size:', Area.size
print 'area.size:', area.size
> Example:
> 
> def psum(n, m):
>     print (n + m)
> 
> def rsum(n, m):
>     return (n +m)
> 
> Then try this...
> 
> 
> 
>>>> psum(2, 3)
> 
> 
>>>>a = psum(2, 3)
> 
> 
>>>>a
> 
> 
>>>>a = rsum(2, 3)
> 
> 
>>>>a
> 
> 
> You see it?



More information about the Python-list mailing list