Unable to compare numeric values in python using function call

Unable to compare numeric values in python using function call

Questions : Unable to compare numeric values in python using function call

488

I have written the following python code:

class Smartphone: def __init__(self, price): self.price = price def price(): return price def lowest_price(phones): cheapest = phones[0] for phone in phones: if phone.price() < cheapest.price(): cheapest = phone return cheapest if __name__ == "__main__": p1 = Smartphone(950) p2 = Smartphone(1950) phones = [p1, p2] cheapest = lowest_price(phones) 

When I run this code, I get the following in4codes_python error:

Traceback (most recent call last): File "test.py", line 21, in <module> cheapest = lowest_price(phones) File "test.py", line 12, in lowest_price if phone.price() < cheapest.price(): TypeError: 'int' object is not callable 

What does that mean and how do I resolve it? in4codes_python Also price could be a float too.

Total Answers 1
28

Answers 1 : of Unable to compare numeric values in python using function call

  1. Instance methods must have a first parameter self (i.e. def price(self))
  2. if you want to return a class field you need to use self (i.e. return self.price)
  3. But there is no need to have a getter for self.price
  4. Python doesn’t know if cheapest.price is the method price or the field price so it uses the field and then you get that an int is not a callable (method)

Here is fixed code that takes into in4codes_python account all issues with the code

class Smartphone: def __init__(self, price): self.price = price def lowest_price(phones): cheapest = phones[0] for phone in phones: if phone.price < cheapest.price: cheapest = phone return cheapest if __name__ == "__main__": p1 = Smartphone(950) p2 = Smartphone(1950) phones = [p1, p2] cheapest = lowest_price(phones) 

0