473,830 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to make a function associated with a class?

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.
Jul 1 '08 #1
7 1172
On 1 juil, 22:43, Kurda Yon <kurda...@yahoo .comwrote:
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(othe r, 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(othe r, 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
Jul 1 '08 #2
On Jul 1, 5:01 pm, "bruno.desthuil li...@gmail.com "
<bruno.desthuil li...@gmail.com wrote:
On 1 juil, 22:43, Kurda Yon <kurda...@yahoo .comwrote:
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(othe r, 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(othe r, 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?
Jul 1 '08 #3
On Jul 1, 1:43 pm, Kurda Yon <kurda...@yahoo .comwrote:
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.
It sounds like you are talking about data-directed programming (see
http://mitpress.mit.edu/sicp/full-te...l#%_sec_2.4.3).
Basically you have two options:

def dot(x,y):
if isinstance(x,Ve ctor) and isintance(y,Vec tor):
...
raise TypeError("..." )

which quickly breaks down in a mess of if-then clauses when you want
to expand the dot function to handle other datatypes, or you create a
table and populate it with entries like this
dispatch_table[('dot','Vector' ,'Vector')] = Vector.dot # this has to
be declared @staticmethod in class Vector
dispatch_table[('dot','str','s tr')] = operator.add # borrowed from PHP
dispatch_table[('mul',Matrix,M atrix)] = Matrix.mul

You now have to write something like this (this isn't even valid
Python code, but hopefully you get the idea)

def generic_functio n(name):
def exec_generic_fu nction(*args):
f = dispatch_table. get((name, *(type(arg).__n ame__ for arg in
args)),None)
if f == None:
raise TypeError('...' )
return f(*args)
return exec_generic_fu nction

dot = generic_functio n('dot')

# NB: (a, *b) means (a,) + b until the generalized *-unpacking syntax
is accepted

This is essentially a translation into Python of the content of the
link.

Neither of these options are great (and the latter is marginal at
best) if you care about performance (but maybe it will all become C
anyway so you don't care). If you want to do it the Python way, use
__mul__.

Cheers,
David
Jul 1 '08 #4
On Jul 1, 2:24 pm, Kurda Yon <kurda...@yahoo .comwrote:
>
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?
$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
>>help(type)
[...]
>>help(isinstan ce)
[...]
Jul 1 '08 #5
On Jul 1, 2:43 pm, Kurda Yon <kurda...@yahoo .comwrote:
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
Jul 2 '08 #6
Kurda Yon a écrit :
On Jul 1, 5:01 pm, "bruno.desthuil li...@gmail.com "
<bruno.desthuil li...@gmail.com wrote:
>On 1 juil, 22:43, Kurda Yon <kurda...@yahoo .comwrote:
>>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(othe r, 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(othe r, 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 ?-)
Jul 2 '08 #7
In article
<0d************ *************** *******@8g2000h se.googlegroups .com>,
Kurda Yon <ku******@yahoo .comwrote:
On Jul 1, 5:01 pm, "bruno.desthuil li...@gmail.com "
<bruno.desthuil li...@gmail.com wrote:
On 1 juil, 22:43, Kurda Yon <kurda...@yahoo .comwrote:
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(othe r, 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(othe r, 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
Jul 7 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2725
by: DaKoadMunky | last post by:
I was recently looking at some assembly code generated by my compiler. When examining the assembly code associated with constructors I noticed that the dynamic-dispatch mechanism was enabled before member initialization but after base initialization. To speak in implementation details the virtual function table pointer for objects being constructed was set before member initialization but after base initialization. Curiousity then...
3
1770
by: John J | last post by:
I am in the process of writing 3 associated classes to store details of yacht racing information. Below is a section of code from my Entry class. An entry object is created as follows "Entry e1 (&r1, &y1,1,"22:30");" The &r1 is a reference to an associated Race object (Race class) and &y1 is a reference to an associated Yacht object (Yacht class). The 1 is a place ie, 1 = first, and "22:30" is the finish time. I wish to add a function to...
2
3376
by: John J | last post by:
I have written the following overload of operator << as a display function. In the code I unsuccessfully try and call a function within another class(<< "Race : " << r->Show () << endl). The Show function is in a class called Race which is also included below. I'd greatly appreciate some guidance on what I'm doing wrong. Thanks for any help ostream& operator<< (ostream& out, const Entry& e)
1
1786
by: Renato T. Forti | last post by:
Hi all, How to access API function of a Managed C++ application? Sample:
4
4525
by: Adriano Coser | last post by:
I'm getting the following error: error C3767: PictureSource - candidate function(s) not accessible when accessing a public member function of a managed class, either from managed or unmanaged code. The class is an owner draw control implemented into a Control Library. The access is on a DLLs that support CLR with old syntax. The code compiled OK on Beta-1.
28
2960
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
7
2707
by: Steven Bethard | last post by:
I've updated PEP 359 with a bunch of the recent suggestions. The patch is available at: http://bugs.python.org/1472459 and I've pasted the full text below. I've tried to be more explicit about the goals -- the make statement is mostly syntactic sugar for:: class <name> <tuple>: __metaclass__ = <callable>
4
2137
by: Chris F Clark | last post by:
Please excuse the length of this post, I am unfortunately long-winded, and don't know how to make my postings more brief. I have a C++ class library (and application generator, called Yacc++(r) and the Language Objects Library) that I have converted over to C#. It works okay. However, in the C# version, one has to build the class library into the generated application, because I haven't structured this one thing right. I would like to...
4
1623
by: Gary | last post by:
I'm a bit confused hopefuly someone can help. I have a text file which stores names and an associated number. Each line in the text file represents one person, and a semicolon ' ; ' seperates person from associated number. The associated number is used as a que position reference (i.e. the person next has the lowest number.) Here is an example: -
0
10769
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10479
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10523
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10199
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7741
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6948
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5616
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5778
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3956
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.