How to make a function associated with a class?

Victor Noagbodji noagbodjivictor at gmail.com
Tue Jul 1 23:44:27 CEST 2008


>
> 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.
>
> Do you think a static method will do the thing?
>

Well you can define the function inside the class.
Then create a name outside the class that references it. Is is.

dot = Class.dot.

By the way, why do you want to tie this function to the class?


-- 
NOAGBODJI Paul Victor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080701/55568cdd/attachment.html>


More information about the Python-list mailing list