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: -
class Particle:
-
def __init__(self, symbol, charge, number):
-
self.symbol = symbol
-
self.charge = charge
-
self.number = number
-
def __repr__(self):
-
return self.symbol
-
class Nucleus(Particle):
-
def __repr__(self):
-
return "(%d)%s" % (self.number, self.symbol)
-
class UnbalancedCharge:
-
pass #worry about this later
-
class UnbalancedNumber:
-
pass #worry about this later
-
-
class Reaction: # this is the class I'm having trouble with
-
def __init__(symbol, charge, number):
-
lhs = number, symbol
-
rhs = number, symbol
-
print lhs # just a test
-
#def __repr__(lhs, rhs): //this is what I'll return later, when I get lhs and rhs to access correct information
-
#return lhs, rhs
-
-
if __name__ == '__main__':
-
em = Particle("e-", -1, 0)
-
ep = Particle("e+", 1, 0)
-
p = Particle("p", 1, 1)
-
n = Particle("n", 0, 1)
-
neutrino = Particle("nu_e", 0, 0)
-
gamma = Particle("gamma", 0, 0)
-
print em, ep, p, n, neutrino, gamma
-
d = Nucleus("H", 1, 2)
-
li6 = Nucleus("li", 3, 6)
-
he4 = Nucleus("He", 2, 4)
-
print d
-
print li6
-
print he4
-
print Reaction((li6, d), (he4, he4))
-
-
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
13 6656 bvdet 2,851
Expert Mod 2GB
You are mismatching your arguments: - class Reaction:
-
def __init__(self, lhs, rhs):
-
self.lhs = lhs
-
self.rhs = rhs
Now self.lhs and self.rhs are tuples. To print the elements: - self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1]
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). -
class Reaction:
-
def __init__(self, lhs, rhs):
-
self.lhs = lhs
-
self.rhs = rhs
-
def __repr__ (self):
-
return self.lhs[0], "+", self.lhs[1], "->", self.rhs[0], "+", self.rhs[1]
-
-
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.
:(
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). -
class Reaction:
-
def __init__(self, lhs, rhs):
-
self.lhs = lhs
-
self.rhs = rhs
-
def __repr__ (self):
-
return self.lhs[0], "+", self.lhs[1], "->", self.rhs[0], "+", self.rhs[1]
-
-
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 -
....
-
def __repr__ (self):
-
s = "%s+%s->%s+%s" %(self.lhs[0],self.lhs[1],self.rhs[0],self.rhs[1])
-
return s
-
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: -
"""
-
Assignment: Homework #6
-
Create a class called Reaction, will have a left hand side and right hand side, specified by tuples
-
containing one or more particles (including Nucleuses). The reaction taking place transofrms
-
the particles on the left-hand side to the particles on the right hand side.
-
"""
-
class Particle:
-
def __init__(self, symbol, charge, number):
-
self.symbol = symbol
-
self.charge = charge
-
self.number = number
-
-
def __add__(left, right):
-
"""
-
#2. Extend the Particle class to have the "+" operator acting on two particles
-
result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
-
equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
-
the correct format.
-
"""
-
return left, right
-
def __repr__(self):
-
return self.symbol
-
-
class Nucleus(Particle):
-
def __repr__(self):
-
return "(%d)%s" % (self.number, self.symbol)
-
class UnbalancedCharge:
-
pass #worry about this later
-
class UnbalancedNumber:
-
pass #worry about this later
-
class Reaction:
-
def __init__(self, lhs, rhs):
-
"""
-
Initialize the left hand side and right hand side so that print Reaction(li6, d)(he4, he4)
-
will produce (6)LI + (2)H -> (4)He + (4)He
-
"""
-
self.lhs = lhs
-
self.rhs = rhs
-
def __repr__ (self):
-
s = "%s+%s->%s+%s" % (self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1])
-
return s
-
class chainReaction(Reaction):
-
def __init__(self, name):
-
self.name = name
-
def chain(self, lhsNet, rhsNet):
-
pass #combine
-
def __repr__ (self):
-
return "%s %s" % (self.name, "chain:" )
-
-
if __name__ == '__main__':
-
em = Particle("e-", -1, 0)
-
ep = Particle("e+", 1, 0)
-
p = Particle("p", 1, 1)
-
n = Particle("n", 0, 1)
-
neutrino = Particle("nu_e", 0, 0)
-
gamma = Particle("gamma", 0, 0)
-
print em, ep, p, n, neutrino, gamma
-
d = Nucleus("h", 1, 2)
-
li6 = Nucleus("li", 3, 6)
-
he4 = Nucleus("he", 2, 4)
-
print d
-
print li6
-
print he4
-
print Reaction((li6, d), (he4, he4))
-
print Reaction(li6 + d, he4 + he4)
-
he3 = Nucleus("he", 2, 3)
-
chnPP = chainReaction("proton-proton (branch I)")
-
print chnPP
-
print Reaction(li6 + d + he4) #this one gives me trouble
-
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: -
-
def __addMore__(left, right, middle):
-
return left, right, middle
-
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?
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: -
"""
-
Assignment: Homework #6
-
Create a class called Reaction, will have a left hand side and right hand side, specified by tuples
-
containing one or more particles (including Nucleuses). The reaction taking place transofrms
-
the particles on the left-hand side to the particles on the right hand side.
-
"""
-
class Particle:
-
def __init__(self, symbol, charge, number):
-
self.symbol = symbol
-
self.charge = charge
-
self.number = number
-
-
def __add__(left, right):
-
"""
-
#2. Extend the Particle class to have the "+" operator acting on two particles
-
result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
-
equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
-
the correct format.
-
"""
-
return left, right
-
def __repr__(self):
-
return self.symbol
-
-
class Nucleus(Particle):
-
def __repr__(self):
-
return "(%d)%s" % (self.number, self.symbol)
-
class UnbalancedCharge:
-
pass #worry about this later
-
class UnbalancedNumber:
-
pass #worry about this later
-
class Reaction:
-
def __init__(self, lhs, rhs):
-
"""
-
Initialize the left hand side and right hand side so that print Reaction(li6, d)(he4, he4)
-
will produce (6)LI + (2)H -> (4)He + (4)He
-
"""
-
self.lhs = lhs
-
self.rhs = rhs
-
def __repr__ (self):
-
s = "%s+%s->%s+%s" % (self.lhs[0], self.lhs[1], self.rhs[0], self.rhs[1])
-
return s
-
class chainReaction(Reaction):
-
def __init__(self, name):
-
self.name = name
-
def chain(self, lhsNet, rhsNet):
-
pass #combine
-
def __repr__ (self):
-
return "%s %s" % (self.name, "chain:" )
-
-
if __name__ == '__main__':
-
em = Particle("e-", -1, 0)
-
ep = Particle("e+", 1, 0)
-
p = Particle("p", 1, 1)
-
n = Particle("n", 0, 1)
-
neutrino = Particle("nu_e", 0, 0)
-
gamma = Particle("gamma", 0, 0)
-
print em, ep, p, n, neutrino, gamma
-
d = Nucleus("h", 1, 2)
-
li6 = Nucleus("li", 3, 6)
-
he4 = Nucleus("he", 2, 4)
-
print d
-
print li6
-
print he4
-
print Reaction((li6, d), (he4, he4))
-
print Reaction(li6 + d, he4 + he4)
-
he3 = Nucleus("he", 2, 3)
-
chnPP = chainReaction("proton-proton (branch I)")
-
print chnPP
-
print Reaction(li6 + d + he4) #this one gives me trouble
-
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: -
-
def __addMore__(left, right, middle):
-
return left, right, middle
-
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.
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
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! - def __add__(self, p2):
-
"""
-
#2. Extend the Particle class to have the "+" operator acting on two particles
-
result in a tuple containing them, so that print Reaction(li6+d, he4 + he4) is
-
equivalent to print Reaction((li6, d), (he4, he4)), this uses class Reaction to print out
-
the correct format.
-
"""
-
if isinstance(p2, tuple):
-
return (self,) + p2
-
else:
-
return self, p2
You will need to use parentheses such that you are adding two instances or one instance and one tuple. - print li6+d
-
print li6+(d+he4)
-
print he4+(he4+(he4+(he4+(he4+he4))))
-
# Yields:
-
>>> ((6)Li, (2)H)
-
((6)Li, (2)H, (4)He)
-
((4)He, (4)He, (4)He, (4)He, (4)He, (4)He)
-
>>>
Not ideal but seems to work.
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.
:)
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!
Ok guys, it's time for me to rename this thread. Either of you have a preference?
yes, I was thinking it would be appropriate to rename it also. How about
overload __add__
or something similar?
yes, I was thinking it would be appropriate to rename it also. How about
overload __add__
or something similar?
You got it! Thanks.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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;
}...
|
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...
|
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...
|
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:
...
|
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...
|
by: Ronny Mandal |
last post by:
Can someone please explain or point me to articles regarding these two
methods?
Thanks.
|
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...
|
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 ):...
|
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...
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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...
|
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,...
|
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...
|
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...
|
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...
|
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,...
| |