class methods vs. functions

Christopher T King squirrel at WPI.EDU
Wed Jul 14 15:38:40 EDT 2004


On 14 Jul 2004, beliavsky at aol.com wrote:

> What are the pros and cons of defining a method of a class versus defining
> a function that takes an instance of the class as an argument? In the example
> below, is it better to be able to write 
> z.modulus() or modulus(z)? Is there a difference between Python and C++ in
> this regard?

The answer to this, as for most questions in computer science, is "it 
depends". :) The answer (which is partially my opinion) has to do with 
interfaces, and what you want to accomplish:

- Case 1 -

All of your objects conform to the 'xy' interface. This interface 
requeries that an object has both .x and .y member variables. You can then 
define a 'modulus' function that is defined to operate on any object 
implementing the 'xy' interface:

> def modulus(z):
>     return sqrt(z.x**2 + z.y**2)

Upside:

No matter what the object is, or from where it comes, so long as it 
implements the 'xy' interface, you can now take the modulus of it.

Downside:

You can't take the modulus of anything that doesn't implement 'xy'.

- Case 2 -

Some of your objects implement the 'xy' interface, others don't (e.g. they 
don't make sense with it). Either way, you want to be able to find their 
modulus. You can do this by making all your objects conform to the 
'modulus' interface. This interface requires that an object have a 
.modulus() member function:

> 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)

Upside:

You can take the modulus of any object you create, regardless of whether 
it can implement the 'xy' interface or not.

Downside:

If you aren't the designer of the object, you can't take the modulus of
it, even if it does implement the 'xy' interface.

So, the choice is up to you. You can always provide both, though:

def mymodulus(z):
    try:
        return z.modulus()
    except AttributeError:
        return modulus(z)

In case you can't tell, I'm as undecided on the issue as you ;)




More information about the Python-list mailing list