How to make a function associated with a class?

John Roth johnroth1 at gmail.com
Tue Jul 1 21:39:47 EDT 2008


On Jul 1, 2:43 pm, 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?
>
> Thank you in advance.

If I understand what you want, you could do it the same way most of
the other functions are implemented. There's a function, and then each
class which has the behavior has a private (actually a system) method
that implements it.

The general pattern is to get the class for the first operand, check
to see if it has the implementation method, and call it if present. If
it doesn't, get the class for the other operand, check and if it has
the method call it with the operands reversed.

Then if it isn't in either, you can look the actual implementation
method up in a table. When all else fails, raise a type error.

HTH

John Roth



More information about the Python-list mailing list