How to make a function associated with a class?

David C. Ullrich dullrich at sprynet.com
Mon Jul 7 17:19:33 EDT 2008


In article 
<0d9c534b-8720-4363-b3e5-eb546dd3637c at 8g2000hse.googlegroups.com>,
 Kurda Yon <kurdayon at yahoo.com> wrote:

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

You want to say dot(x,y), but to have the actual behavior
determined by the class of which x and y are instances?
You could do this:

def dot(x,y):
  return x.dot(y)

and now give Vector an appropriate dot(self, other) method.

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

-- 
David C. Ullrich



More information about the Python-list mailing list