|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
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) return self.total 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: 11111111111111111111 Any ideas! |
|
#2
|
|||
|
|||
|
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.
|
|
#3
|
|||
|
|||
|
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.
example: '11' * 10 prints out: '11111111111111111111' |
|
#4
|
|||
|
|||
|
Yeah, that was the problem. I just used the repr() function to convert into integers and that seems to have sorted it.
Thanks. |
|
#5
|
|||
|
|||
|
Quote:
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) |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > RE: Problem with method in class |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|