April 2nd, 2003, 04:31 AM
RE: Problem with method in class
Can someone please advise what I'm doing wrong with the following method. As an introduction, I've got a class containing currency of various denominations, which need to be added up and a total obtained. The method which I am confused on is supposed to convert each denomination of currency to the lowest value of the currency i.e. 'lambs' in my example. The problem is that when I start timesing (*) an attribute in my class, I get a huge number, much longer then the correct result. The code I am confused about is as follows:
def getTotal (self):
self.total = self.lamb * 10 + (self.bleat * 10) + (self.frolic * 50) + (self.ram * 100)
In running a test, I commented out everything after self.bleat*10)... and then ran the program typing the values 1 for lamb and 1 for bleat. When the total is printed I expected a result of 11, but instead the result came out as:
April 2nd, 2003, 02:08 PM
Looks like you are multiplying strings on accident, perhaps. Make sure that when you are doing multiplication that you cast strings to ints or floats.
April 3rd, 2003, 08:29 PM
ya I'd check and make sure that your numbers aren't strings, because if they are, it would just print out the string multiple times depending on the number you multiplied it with.
'11' * 10
April 4th, 2003, 12:09 AM
Yeah, that was the problem. I just used the repr() function to convert into integers and that seems to have sorted it.
April 4th, 2003, 05:40 PM
repr() is fine, but I think maybe int() would be more appropriate as I think it would raise better Exceptions and would make the intentions more clear (repr() may silently convert something to a datatype you don't want to like a list or something whereas int() places more constraints on what the data can be)