Re: classes vs. modules vs. types

lance@fox.com
Mon, 2 May 94 18:29:13 PDT

> Date: Mon, 02 May 94 20:15:45 -0400
> From: Tim Peters <tim@ksr.com>
>
> Skip, in the C++ sense, _all_ Python class methods are "virtual". That's
> why you don't see any funny syntax in Lance's example declaring getarea
> as virtual. His _convention_ for "declaring" it virtual is nice:
>
> class shape:
> ...
> def getarea(self):
> raise NameError, 'getarea() must be overridden'
>
> A more-obscure-but-less-work strategy is simply not to define
> shape.getarea at all. Then an object of a class derived from shape that
> doesn't define its own getarea method, but attempts to invoke getarea
> anyway, will trigger a runtime NameError exception.

Yes. I could have just left it out, but I prefer to have a little
"custom" message instead of just "name does not exist" type messages.
Also, when you are looking at the class 'shape', you can find out what
methods you need to code to "complete" a basic shape.

> One bug:
>
> > import shape
> > cir = shape.circle(5)
> > ...
> > print cir.getarea() # print area of circle
>
> That prints a number close to 22.0, which would be right if pi were about
> 0.88 <wink>.
>
> The problem is in:
>
> class circle(shape):
> ...
> def getarea(self):
> return 3.14159 * (self.radius ^ 2)
>
> That's actually doing an xor on self.radius and 2. Clearest is probably
>
> from math import pi
> ...
> class circle(shape):
> ...
> def getarea(self):
> return pi * pow(self.radius, 2)

Thanks... sometimes I don't think things through 100% and I did not
test the code completely.

--
Lance Ellinghouse                lance@fox.com