Python OOP入门遇类型错误:'int'与'Toy'实例无法比较'<'
解决Python OOP插入排序中的类型错误
嘿,我一眼就揪出问题所在啦!先给你拆解下这个报错:TypeError: '<' not supported between instances of 'int' and 'Toy'——这说明你在比较时不小心把整数和Toy对象直接放一起比了,根源就在插入排序的代码里。
错误原因分析
看这段出问题的代码:
x[i+1].SetPrice(x[i])
SetPrice方法需要传入的是价格数值(比如整数),但你这里直接传了x[i]——这可是一个Toy类的实例对象,不是价格数值!当你把对象传给SetPrice后,x[i+1]的__price属性就变成了Toy对象,后面再执行value < x[i].GetPrice()时,一边是整数(value是价格),另一边如果某个元素的__price已经被改成了对象,自然就触发了类型不匹配的错误。
修正后的完整代码
把那行错误代码改成传入价格数值就行,也就是调用GetPrice()获取价格再传进去:
class Toy: def __init__(self, price): self.__price = price def SetPrice(self, p): self.__price = p def GetPrice(self): return self.__price def InsertionSort(x): for index in range(1, len(x)): current_toy = x[index] value = current_toy.GetPrice() i = index - 1 while i >= 0: if value < x[i].GetPrice(): # 传入前一个玩具的价格数值,而非对象本身 x[i+1].SetPrice(x[i].GetPrice()) x[i].SetPrice(value) i = i - 1 else: break # 测试示例:创建几个Toy实例 prices = [] prices.append(Toy(50)) prices.append(Toy(20)) prices.append(Toy(80)) InsertionSort(prices) # 打印排序后的价格 for toy in prices: print(toy.GetPrice())
更Pythonic的优化建议
在Python里,咱们一般不用传统的GetXXX/SetXXX方法,而是用@property装饰器来实现属性的访问和修改,代码会更简洁易读:
class Toy: def __init__(self, price): self.__price = price @property def price(self): return self.__price @price.setter def price(self, p): self.__price = p # 改造后的排序函数,直接用属性访问更直观 def InsertionSort(x): for index in range(1, len(x)): value = x[index].price i = index - 1 while i >= 0: if value < x[i].price: x[i+1].price = x[i].price x[i].price = value i = i - 1 else: break
这样写不仅符合Python的风格,还能减少因为方法调用疏忽导致的错误哦~
内容的提问来源于stack exchange,提问作者Kaya
相关产品推荐
相关产品推荐

