class methods vs. functions

A B Carter gnosticray at
Fri Jul 16 10:23:52 CEST 2004

"beliavsky at" <beliavsky at> wrote 
> from math import sqrt
> class xy:
>     def __init__(self,x,y):
>         self.x = x
>         self.y = y
>     def modulus(self):
>         return sqrt(self.x**2 + self.y**2)
> def modulus(z):
>     return sqrt(z.x**2 + z.y**2)
> z = xy(3,4)
> print z.modulus()
> print modulus(z)

In the example given the use of a function is IMHO a straightforward
mistake. The rivers will not run with blood if you do this, but it is
nonetheless a clear violation of basic OO design.

By using a function you're implying that it will work, if not with all
objects then with some wide range of semi-generic or base objects. But
most objects will not have x and y attributes. In other cases an
object may have such attributes but store string values or possess
attributes that could be sensibly used as arguments to a modulus
function but have the wrong names. A fundamental insight of the OO
approach is the benefit of associating a data structure with a set of
methods that work with that data structure. By incorporating modulus
as a method in the xy class you avoid the problems mentioned above.

It makes sense to have functions that work with all objects, such as
the id() function or they work with basic Python types such as numeric
values. A modulus function would be fine if it took two numeric values
and returned the square root of the sum of their squares, but it would
then be just the math.hypot function.

Python does place a premium on rapid prototyping and in consequence
possesses an OO implementation that doesn't get in the way of coding.
The joy of Python is that you can usually concentrate on the problem
and not be distracted by the need to satisfy additional requirements
of OO purity. However Python is an OO language; all of the standard
concepts still apply and all of the usual guidelines should still be
followed. You still write to the interface, you still encapsulate your
data and you still associate methods with data structures. This isn't
a matter of OO orthodoxy but of practical design that led to the
development of OO.

A B Carter

More information about the Python-list mailing list