TypeError:'

问题描述 投票:0回答:1

我是python OOP的新手,我正在努力解决这段代码中的错误,如果有人可以提供帮助那就太棒了!

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)):
            value = x[index].GetPrice()
            i = index -1
            while i >= 0:

                if value < (x[i].GetPrice()):
                    x[i+1].SetPrice(x[i])  
                    x[i].SetPrice(value)
                    i = i -1
                else:
                    break

prices = []
prices.append(Toy(200))
prices.append(Toy(10))
prices.append(Toy(20))

Toy.InsertionSort(prices)

但是当我运行它时,我得到了回复,但是我并不真正理解错误意味着什么,我已经尝试过以其他方式编写它,但我不知道现在该做什么。

Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py", 
line 34, in <module>
Toy.InsertionSort(prices)
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py", 
line 20, in InsertionSort
if value < (x[i].GetPrice()):
TypeError: '<' not supported between instances of 'int' and 'Toy'

先感谢您!

python python-3.x oop
1个回答
8
投票

问题是因为这条线

x[i+1].SetPrice(x[i])  

x[i+1]设置为x[i],这是一个Toy,而不是int。

© www.soinside.com 2019 - 2024. All rights reserved.