以下是我的代码片段。当我运行该程序时,出现以下错误。
@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/