1

以下是我的代码片段。当我运行程序时,它给了我以下错误。

 @functools.total_ordering
 AttributeError: 'module' object has no attribute 'total_ordering'

我正在使用 python 3.1

import functools

@functools.total_ordering
class Abs(object):
    def __init__(self,num):
        self.num=abs(num)
    def __eq__(self,other):
        return self.num==abs(other.num)
    def __lt__(self,other):
        return self.num < abs(other.num)

five=Abs(-5)
four=Abs(-4)
print(five > four)

导入语句中是否缺少某些内容?

4

1 回答 1

2

不,您的导入声明很好。问题是您的 Python 安装落后了一个版本。 functools.total_ordering在 Python 3.2 中添加。从文档

3.2 版中的新功能。

在 3.4 版更改:NotImplemented现在支持从底层比较函数返回无法识别的类型。

因此,您需要升级才能使用它。如果这不可能,那么您只需要手动定义所有比较运算符。

请注意,此装饰器也向后移植到 Python 2.7,但我假设您希望保留 Python 3.x。

于 2014-12-18T03:03:53.320 回答