How to make a function associated with a class?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Jul 2 04:34:46 EDT 2008


Kurda Yon a écrit :
> 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)".

I tought you could figure it out by yourself from the above examples.


> By the way, "type(self)" returns the name of the class to which the
> "self" belongs?

Nope, it returns the class object (for new-style classes at least).

> Does "instance"  return "true" if the first argument belongs to the
> class whose name

Python's classes are objects. type() returns a class object (or a type 
object for old-style classes IIRC), and isinstance() takes a class or 
style object (or a tuple of class / type objects) as second argument.

> is given in the second argument?

isinstance() is documented, you know ? As well as type() FWIW. What 
about first looking up the fine manual, then come back if there's 
something you have problem with ?-)



More information about the Python-list mailing list