How to make a function associated with a class?
Kurda Yon
kurdayon at yahoo.com
Tue Jul 1 23:24:48 CEST 2008
On Jul 1, 5:01 pm, "bruno.desthuilli... at gmail.com"
<bruno.desthuilli... at gmail.com> wrote:
> 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
As far as I understood, In the first case, you gave, I need to call
the function as follows "x.dot(y)". In the second case I need to call
the function as follows "x*y". But I want to call the function as
follows "dot(x,y)".
By the way, "type(self)" returns the name of the class to which the
"self" belongs?
Does "instance" return "true" if the first argument belongs to the
class whose name is given in the second argument?
More information about the Python-list
mailing list