Re: classes vs. modules vs. types

Tim Peters (
Mon, 02 May 94 20:15:45 -0400

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.

One bug:

> import shape
> cir =
> ...
> 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)

The "from math import pi" line imports math.pi, and binds it to the name
"pi" in the module namespace. One reason to package related classes in
the same file (== module) is to allow easy access to common global values
(like "pi" above) across the classes in the file. Might help to think of
"the module namespace" as C's file-scope static (although any module
_can_ reach into any other module's namespace, if it wants to).

circularly y'rs - tim

Tim Peters
not speaking for Kendall Square Research Corp