我编写了以下python代码:
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)当我运行这段代码时,我会得到以下错误:
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这意味着什么,我该如何解决呢?此外,价格也可能是浮动的。
发布于 2021-12-13 23:55:27
def price(self))
self (即要返回需要使用self的类字段的self.price
self.price
self.price
cheapest.price是方法price还是字段price,所以它使用字段,然后得到int不是callable (方法)H 218G 219下面是考虑到代码中所有问题的固定代码
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)https://stackoverflow.com/questions/70342219
复制相似问题