【发布时间】:2019-08-16 01:36:39
【问题描述】:
我尝试写一个小班,想根据重量对项目进行排序。代码已提供,
class Bird:
def __init__(self, weight):
# __weight for the private variable
self.__weight = weight
def weight(self):
return self.__weight
def __repr__(self):
return "Bird, weight = " + str(self.__weight)
if __name__ == '__main__':
# Create a list of Bird objects.
birds = []
birds.append(Bird(10))
birds.append(Bird(5))
birds.append(Bird(200))
# Sort the birds by their weights.
birds.sort(lambda b: b.weight())
# Display sorted birds.
for b in birds:
print(b)
当我运行程序时,我得到了Python TypeError: sort() takes no positional arguments 的错误堆栈。这里有什么问题?
【问题讨论】:
-
这个错误实际上是针对 python3 的。 Python2 会假设给 sort 的函数是 cmp 函数。上面的代码仍然会因为你给它一个键功能而中断。我发现这个 Q 是因为我的 python2 脚本在 python3 下运行时损坏了。
标签: python python-3.x class sorting arguments