How to make a function associated with a class?

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Tue Jul 1 17:01:40 EDT 2008


On 1 juil, 22:43, Kurda Yon <kurda... at yahoo.com> wrote:
> Hi,
>
> I have a class called "vector". And I would like to define a function
> "dot" which would return a dot product of any two  "vectors". I want
> to call this function as follow: dot(x,y).
>
> Well, I can define a functions "dot" outside the class and it works
> exactly as I want. However, the problem is that this function is not
> associated with the class (like methods a method of the class).
>
> For example, if I call "x.calc()" or "y.calc()", python will execute
> different methods if "x" and "y" belongs to different classes. I want
> to have the same with my "dot" function. I.e. I want it calculates the
> dot product ONLY IF the both arguments of that function belong to the
> "vector" class.
>
> Is it possible?

You don't need to make dot() a method of your Vector class to have
this behaviour, and making it a method of the Vector class isn't
enough to have this behaviour.

The simplest solution would be:

class Vector(object):
    def dot(self, other):
        if not isinstance(other, type(self)):
            raise TypeError("can only calculate the dot product of two
vectors")
        # do the job here and return what's appropriate

Now since it's a binary operator, you might as well implement it as
such:

class Vector(object):
    def __mul__(self, other):
        if not isinstance(other, type(self)):
            raise TypeError("can only calculate the dot product of two
vectors")
        # do the job here and return what's appropriate

Then use it as doproduct = vector1 * vector2


HTH



More information about the Python-list mailing list