Re: classes vs. modules vs. types

lance@fox.com
Mon, 2 May 94 15:54:52 PDT

> From: Skip Montanaro <montnaro@spyder.crd.ge.com>
> Date: Mon, 2 May 1994 17:35:40 GMT
>
>
> I'm just getting started with Python and am wondering what distinctions, if
> any, there are between modules, classes, and built-in types. I'm interested
> in understanding how I might integrate C++ classes into Python. To add some
> concreteness to my problem, suppose I have a simple C++ class hierarchy:
>
> shape
> circle
> rectangle
> triangle
>
> Shape is abstract and defines getcolor() and setcolor() methods, and
> declares a single abstract virtual method, getarea(). Circle, rectangle, and
> triangle must define getarea().

I would create a file called shape.py and this is what it would hold..

---- CUT: shape.py
# This is a sample class system for shapes

class shape:
def __init__(self):
self.color = None
def getcolor(self):
return self.color
def setcolor(self,color):
self.color = color
return None
def getarea(self):
raise NameError, 'getarea() must be overridden'

class circle(shape):
def __init__(self,radius):
self.radius = radius
def getarea(self):
return 3.14159 * (self.radius ^ 2)

class rectangle(shape):
def __init__(self,width,height):
self.width = width
self.height = height
def getarea(self):
return self.width * self.height

class triangle(shape):
def __init__(self,height,base):
self.height = height
self.base = base
def getarea(self):
return (self.height * self.base) / 2
---- CUT

Ok.. now to use this...

import shape
cir = shape.circle(5)
rec = shape.rectangle(5,4)
tri = shape.triangle(5,4)

print cir.getarea() # print area of circle
print rec.getarea() # print area of rectangle
print tri.getarea() # print area of triangle

> Thanks,
>
> --
> Skip (montanaro@crd.ge.com)

Hope this helps...

--
Lance Ellinghouse                lance@fox.com