python - AttributeError functools.total_ordering

标签 python python-3.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)

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

最佳答案

不,您的导入声明没问题。问题是你的Python安装落后了一个版本。 Python 3.2 中添加了 functools.total_ordering。来自 docs :

New in version 3.2.

Changed in version 3.4: Returning NotImplemented from the underlying comparison function for unrecognized types is now supported.

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

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

关于python - AttributeError functools.total_ordering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538577/

相关文章:

batch-file - 如何在Windows中设置默认的Python版本?

python - Django:如何传递变量以包含来自 url 标签的标签?

python - 如何查看AWS Beanstalk应用程序的源代码和项目目录?

python - 获取元组列表第一个索引?

python - Python 中的莫尔斯电码解密器不工作

python - 如何在 Python 3.1 中安装 argparse?

python - 国际象棋引擎类型错误 : unhashable type: 'list'

Python - BaseHTTPServer.HTTPServer 并发和线程

python - IPython:AMPL 必须指向什么才能运行 Gecode?

python - 属性错误 : 'Pool' object has no attribute '__exit__'