473,403 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

overload __add__

TMS
119 100+
OK, I'm building this reactor software (an assignment) that takes particles and shows a chain reaction.

Here is the code I have so far:

Expand|Select|Wrap|Line Numbers
  1. class Particle:
  2.     def __init__(self, symbol, charge, number):
  3.         self.symbol = symbol
  4.         self.charge = charge
  5.         self.number = number
  6.     def __repr__(self):
  7.         return self.symbol
  8. class Nucleus(Particle):
  9.     def __repr__(self):
  10.         return "(%d)%s" % (self.number, self.symbol)
  11. class UnbalancedCharge:
  12.     pass #worry about this later
  13. class UnbalancedNumber:
  14.     pass #worry about this later
  15.  
  16. class Reaction: # this is the class I'm having trouble with
  17.     def __init__(symbol, charge, number):
  18.         lhs = number, symbol
  19.         rhs = number, symbol
  20.         print lhs # just a test
  21.     #def __repr__(lhs, rhs): //this is what I'll return later, when I get lhs and rhs to access correct information
  22.         #return lhs, rhs
  23.  
  24. if __name__ == '__main__':
  25.     em = Particle("e-", -1, 0)
  26.     ep = Particle("e+", 1, 0)
  27.     p = Particle("p", 1, 1)
  28.     n = Particle("n", 0, 1)
  29.     neutrino = Particle("nu_e", 0, 0)
  30.     gamma = Particle("gamma", 0, 0)             
  31.     print em, ep, p, n, neutrino, gamma
  32.     d = Nucleus("H", 1, 2)
  33.     li6 = Nucleus("li", 3, 6)
  34.     he4 = Nucleus("He", 2, 4)
  35.     print d
  36.     print li6
  37.     print he4
  38.     print Reaction((li6, d), (he4, he4))
  39.  
  40.  
The problem is in the Reaction class. It should print out like this:

(6)Li + (2)H -> (4)He + (4)He

Right now its only giving me the following:

e- e+ p n nu_e gamma
(2)H
(6)li
(4)He
(((4)He, (4)He), <__main__.Reaction instance at 0x00C42670>) (((4)He, (4)He), <__main__.Reaction instance at 0x00C42670>)
<__main__.Reaction instance at 0x00C42670>
>>>

The final one starting with (((4)He, (4)He), is the part I don't want and should look like the example I gave.

So, I think I'm going the right direction but its printing the second particles twice, and not using the first particles at all. Plus its giving me the address in memory, and I most definitely don't want that. At first I thought it was inheritance, but I can see now that it isn't. The Nucleus prints the correct format for one particle, so I need to reuse that to make this class print out what I need. Can someone give me a nudge in the right direction, please?

Thanks
Feb 23 '07 #1
13 6656
bvdet
2,851 Expert Mod 2GB
You are mismatching your arguments:
Expand|Select|Wrap|Line Numbers
  1. class Reaction:
  2.     def __init__(self, lhs, rhs):
  3.         self.lhs = lhs
  4.         self.rhs = rhs
Now self.lhs and self.rhs are tuples. To print the elements:
Expand|Select|Wrap|Line Numbers
  1. self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1]
Feb 23 '07 #2
TMS
119 100+
I'm getting an error message with that. Here is what I did (I had already figured out the self.lhs = lhs and I got it to print... but not right).

Expand|Select|Wrap|Line Numbers
  1. class Reaction:
  2.     def __init__(self, lhs, rhs):
  3.         self.lhs = lhs
  4.         self.rhs = rhs
  5.     def __repr__ (self): 
  6.         return self.lhs[0], "+", self.lhs[1], "->", self.rhs[0], "+", self.rhs[1]
  7.  
  8.  
Here is the error:
Traceback (most recent call last):
File "C:\Python25\part.py", line 44, in <module>
print Reaction((li6, d), (he4, he4))
TypeError: __str__ returned non-string (type tuple)

But when I print from __init__ I get this:

((6)li, (2)h) ((4)he, (4)he)

So, I am accessing it, its returning a tuple and I don't know how to fix it.

:(
Feb 23 '07 #3
ghostdog74
511 Expert 256MB
I'm getting an error message with that. Here is what I did (I had already figured out the self.lhs = lhs and I got it to print... but not right).

Expand|Select|Wrap|Line Numbers
  1. class Reaction:
  2.     def __init__(self, lhs, rhs):
  3.         self.lhs = lhs
  4.         self.rhs = rhs
  5.     def __repr__ (self): 
  6.         return self.lhs[0], "+", self.lhs[1], "->", self.rhs[0], "+", self.rhs[1]
  7.  
  8.  
Here is the error:
Traceback (most recent call last):
File "C:\Python25\part.py", line 44, in <module>
print Reaction((li6, d), (he4, he4))
TypeError: __str__ returned non-string (type tuple)

But when I print from __init__ I get this:

((6)li, (2)h) ((4)he, (4)he)

So, I am accessing it, its returning a tuple and I don't know how to fix it.

:(

how about this
Expand|Select|Wrap|Line Numbers
  1. ....
  2. def __repr__ (self):     
  3.     s = "%s+%s->%s+%s" %(self.lhs[0],self.lhs[1],self.rhs[0],self.rhs[1])
  4.     return s
  5.  
Feb 24 '07 #4
TMS
119 100+
ah... thank you
Feb 24 '07 #5
TMS
119 100+
ok, new problem on this assignment.

For me, this is rather complicated, so I will try to make it as simple as possible. I've gotten the reactor to take in an element, then add 2 elements 2 different ways. Now I need to get it to add 3 different elements. (not really add, just look as if it is adding). Here is my code:

Expand|Select|Wrap|Line Numbers
  1. """
  2. Assignment: Homework #6
  3. Create a class called Reaction, will have a left hand side and right hand side, specified by tuples
  4. containing one or more particles (including Nucleuses). The reaction taking place transofrms
  5. the particles on the left-hand side to the particles on the right hand side.
  6. """
  7. class Particle:
  8.     def __init__(self, symbol, charge, number):
  9.         self.symbol = symbol
  10.         self.charge = charge
  11.         self.number = number
  12.  
  13.     def __add__(left, right):
  14.         """
  15.         #2. Extend the Particle class to have the "+" operator acting on two particles
  16.         result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
  17.         equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
  18.         the correct format.
  19.         """
  20.         return left, right
  21.     def __repr__(self):
  22.         return self.symbol
  23.  
  24. class Nucleus(Particle):
  25.     def __repr__(self):
  26.         return "(%d)%s" % (self.number, self.symbol)
  27. class UnbalancedCharge:
  28.     pass #worry about this later
  29. class UnbalancedNumber:
  30.     pass #worry about this later
  31. class Reaction:
  32.     def __init__(self, lhs, rhs):
  33.         """
  34.         Initialize the left hand side and right hand side so that print Reaction(li6, d)(he4, he4)
  35.         will produce (6)LI + (2)H -> (4)He + (4)He
  36.         """
  37.         self.lhs = lhs
  38.         self.rhs = rhs
  39.     def __repr__ (self):
  40.         s = "%s+%s->%s+%s" % (self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1])
  41.         return s
  42. class chainReaction(Reaction):
  43.     def __init__(self, name):
  44.         self.name = name
  45.     def chain(self, lhsNet, rhsNet):
  46.         pass #combine
  47.     def __repr__ (self):
  48.         return "%s %s" % (self.name, "chain:" )
  49.  
  50. if __name__ == '__main__':
  51.     em = Particle("e-", -1, 0)
  52.     ep = Particle("e+", 1, 0)
  53.     p = Particle("p", 1, 1)
  54.     n = Particle("n", 0, 1)
  55.     neutrino = Particle("nu_e", 0, 0)
  56.     gamma = Particle("gamma", 0, 0)             
  57.     print em, ep, p, n, neutrino, gamma
  58.     d = Nucleus("h", 1, 2)
  59.     li6 = Nucleus("li", 3, 6)
  60.     he4 = Nucleus("he", 2, 4)
  61.     print d
  62.     print li6
  63.     print he4
  64.     print Reaction((li6, d), (he4, he4))
  65.     print Reaction(li6 + d, he4 + he4)
  66.     he3 = Nucleus("he", 2, 3)
  67.     chnPP = chainReaction("proton-proton (branch I)")
  68.     print chnPP
  69.     print Reaction(li6 + d + he4) #this one gives me trouble
  70.  
The last print request is the one I can't seem to figure out. I've tried re-writing the function that is called when I add 2 by adding middle, but it doesn't work. I mean, like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. def __addMore__(left, right, middle):
  3.     return left, right, middle
  4.  
because it works so well for the one that 'adds' two, but it doesn't work. I need this because eventually I have to write a net reaction that combines reactions on the left side, then 'points' to the reactions on the right hand side. One of the reactions for the sun looks like this:

Reaction(p + p, d + ep + neutrino, chnPP)

which has a part with 2 elements, then 3, then the name of the reaction which I defined in a different class. I will do that later, for now I simply need to get the program to add three as the test shows on my code.

Any ideas?
Feb 27 '07 #6
bartonc
6,596 Expert 4TB
ok, new problem on this assignment.

For me, this is rather complicated, so I will try to make it as simple as possible. I've gotten the reactor to take in an element, then add 2 elements 2 different ways. Now I need to get it to add 3 different elements. (not really add, just look as if it is adding). Here is my code:

Expand|Select|Wrap|Line Numbers
  1. """
  2. Assignment: Homework #6
  3. Create a class called Reaction, will have a left hand side and right hand side, specified by tuples
  4. containing one or more particles (including Nucleuses). The reaction taking place transofrms
  5. the particles on the left-hand side to the particles on the right hand side.
  6. """
  7. class Particle:
  8.     def __init__(self, symbol, charge, number):
  9.         self.symbol = symbol
  10.         self.charge = charge
  11.         self.number = number
  12.  
  13.     def __add__(left, right):
  14.         """
  15.         #2. Extend the Particle class to have the "+" operator acting on two particles
  16.         result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
  17.         equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
  18.         the correct format.
  19.         """
  20.         return left, right
  21.     def __repr__(self):
  22.         return self.symbol
  23.  
  24. class Nucleus(Particle):
  25.     def __repr__(self):
  26.         return "(%d)%s" % (self.number, self.symbol)
  27. class UnbalancedCharge:
  28.     pass #worry about this later
  29. class UnbalancedNumber:
  30.     pass #worry about this later
  31. class Reaction:
  32.     def __init__(self, lhs, rhs):
  33.         """
  34.         Initialize the left hand side and right hand side so that print Reaction(li6, d)(he4, he4)
  35.         will produce (6)LI + (2)H -> (4)He + (4)He
  36.         """
  37.         self.lhs = lhs
  38.         self.rhs = rhs
  39.     def __repr__ (self):
  40.         s = "%s+%s->%s+%s" % (self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1])
  41.         return s
  42. class chainReaction(Reaction):
  43.     def __init__(self, name):
  44.         self.name = name
  45.     def chain(self, lhsNet, rhsNet):
  46.         pass #combine
  47.     def __repr__ (self):
  48.         return "%s %s" % (self.name, "chain:" )
  49.  
  50. if __name__ == '__main__':
  51.     em = Particle("e-", -1, 0)
  52.     ep = Particle("e+", 1, 0)
  53.     p = Particle("p", 1, 1)
  54.     n = Particle("n", 0, 1)
  55.     neutrino = Particle("nu_e", 0, 0)
  56.     gamma = Particle("gamma", 0, 0)             
  57.     print em, ep, p, n, neutrino, gamma
  58.     d = Nucleus("h", 1, 2)
  59.     li6 = Nucleus("li", 3, 6)
  60.     he4 = Nucleus("he", 2, 4)
  61.     print d
  62.     print li6
  63.     print he4
  64.     print Reaction((li6, d), (he4, he4))
  65.     print Reaction(li6 + d, he4 + he4)
  66.     he3 = Nucleus("he", 2, 3)
  67.     chnPP = chainReaction("proton-proton (branch I)")
  68.     print chnPP
  69.     print Reaction(li6 + d + he4) #this one gives me trouble
  70.  
The last print request is the one I can't seem to figure out. I've tried re-writing the function that is called when I add 2 by adding middle, but it doesn't work. I mean, like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. def __addMore__(left, right, middle):
  3.     return left, right, middle
  4.  
because it works so well for the one that 'adds' two, but it doesn't work. I need this because eventually I have to write a net reaction that combines reactions on the left side, then 'points' to the reactions on the right hand side. One of the reactions for the sun looks like this:

Reaction(p + p, d + ep + neutrino, chnPP)

which has a part with 2 elements, then 3, then the name of the reaction which I defined in a different class. I will do that later, for now I simply need to get the program to add three as the test shows on my code.

Any ideas?
__add__() and all others with those names are internal to python and are called operator overloads (they let your code resond to operators ("+" in this case)). You don't get to addMore of them to the language. If your __add__() is working correctly, python will do the work: first evaluate d+ep, then add neutrino to the result.
Feb 27 '07 #7
TMS
119 100+
so maybe adding an if statement to the __add__ function? Because sometimes it takes two elements and sometimes 3. If so, I'll have to think for a bit how to logically make that work.

tms
Feb 27 '07 #8
bvdet
2,851 Expert Mod 2GB
so maybe adding an if statement to the __add__ function? Because sometimes it takes two elements and sometimes 3. If so, I'll have to think for a bit how to logically make that work.

tms
Yep!
Expand|Select|Wrap|Line Numbers
  1.     def __add__(self, p2):
  2.         """
  3.         #2. Extend the Particle class to have the "+" operator acting on two particles
  4.         result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
  5.         equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
  6.         the correct format.
  7.         """
  8.         if isinstance(p2, tuple):
  9.             return (self,) + p2
  10.         else:
  11.             return self, p2
You will need to use parentheses such that you are adding two instances or one instance and one tuple.
Expand|Select|Wrap|Line Numbers
  1.     print li6+d
  2.     print li6+(d+he4)
  3.     print he4+(he4+(he4+(he4+(he4+he4))))
  4. # Yields:
  5. >>> ((6)Li, (2)H)
  6. ((6)Li, (2)H, (4)He)
  7. ((4)He, (4)He, (4)He, (4)He, (4)He, (4)He)
  8. >>> 
Not ideal but seems to work.
Feb 27 '07 #9
bvdet
2,851 Expert Mod 2GB
so maybe adding an if statement to the __add__ function? Because sometimes it takes two elements and sometimes 3. If so, I'll have to think for a bit how to logically make that work.

tms
Now you need to get a Reaction() instance to display properly. It only expects two elements on each side, so you need to build the return string allowing for the variable length of tuples on each side. Insead of me posting code, I think you can do it.
Feb 27 '07 #10
TMS
119 100+
:)

I was also toying with __radd__ but couldn't really get that to work. I think I can figure it out from here. Thank you!
Feb 28 '07 #11
bartonc
6,596 Expert 4TB
Ok guys, it's time for me to rename this thread. Either of you have a preference?
Feb 28 '07 #12
TMS
119 100+
yes, I was thinking it would be appropriate to rename it also. How about

overload __add__

or something similar?
Feb 28 '07 #13
bartonc
6,596 Expert 4TB
yes, I was thinking it would be appropriate to rename it also. How about

overload __add__

or something similar?
You got it! Thanks.
Feb 28 '07 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Equis Uno | last post by:
Hi there, I just figured out how to use __add__() to overload the "+" operator for objects of a class. According to googel queries, I see other functions available to me for overloading other...
7
by: Piotre Ugrumov | last post by:
I have tried to implement the overload of these 2 operators. ostream & operator<<(ostream &out, Person &p){ out<<p.getName()<<" "<<p.getSurname()<<", "<<p.getDateOfBirth()<<endl; return out; }...
1
by: Piotre Ugrumov | last post by:
I'm following your help. I have written the overload of the operator <<. This overload work! :-) But I have some problem with the overload of the operator >>. I have written the overload of this...
3
by: Piotre Ugrumov | last post by:
I have done the overload on the operator >> and << in the class Attore. These 2 overload work correctly. I have done the overload of the same overload in the class Film. The class film ha inside...
17
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: ...
9
by: Tony | last post by:
I have an operator== overload that compares two items and returns a new class as the result of the comparison (instead of the normal bool) I then get an ambiguous operater compile error when I...
3
by: Ronny Mandal | last post by:
Can someone please explain or point me to articles regarding these two methods? Thanks.
5
by: jknupp | last post by:
In the following program, if the call to bar does not specify the type as <int>, gcc gives the error "no matching function for call to ‘bar(A&, <unresolved overloaded function type>)’". Since bar...
0
by: Magnus Schuster | last post by:
Hello, I have written the following small proxy class which I expect to pass all function calls to the 'original' object: --- BEGIN --- class proxy(object): def __init__( self, subject ):...
0
by: Magnus Schuster | last post by:
With this explanation the behaviour is absolutely clear. Can I find some documentation anywhere containing more background information how magic functions are resolved? I haven't been successful...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.