Python 2.x有两种方法可以重载比较运算符,__cmp__
或者"丰富的比较运算符",如__lt__
. 丰富的比较超载被认为是首选,但为什么会这样呢?
丰富的比较运算符更容易实现每个,但您必须使用几乎相同的逻辑实现其中几个.但是,如果你可以使用内置cmp
和元组排序,那么__cmp__
变得非常简单并完成所有的比较:
class A(object):
def __init__(self, name, age, other):
self.name = name
self.age = age
self.other = other
def __cmp__(self, other):
assert isinstance(other, A) # assumption for this example
return cmp((self.name, self.age, self.other),
(other.name, other.age, other.other))
Run Code Online (Sandbox Code Playgroud)
这种简单性似乎比重载所有6(!)丰富的比较更好地满足了我的需求.(但是,如果你依赖于"交换的论证"/反映的行为,你可以把它归结为"只是"4,但这导致并发症的净增加,在我的拙见中.)
如果我只是超载,是否有任何不可预见的陷阱需要注意__cmp__
?
我明白了<
,<=
,==
等运营商也可以被重载用于其他目的,并且可以返回任何他们喜欢的对象.我不是在询问这种方法的优点,而是仅仅考虑使用这些运算符进行比较时的差异,这与它们对数字的意义相同.
更新:克里斯托弗指出,cmp
正在消失3.x. 有没有其他方法可以使实施比较变得如上所述__cmp__
?
我正在尝试减少代码中的复制/粘贴,并且偶然发现了这个问题.我已经google了答案但是所有答案都使用类的实例作为键,我找不到任何使用类定义本身作为键(我不知道是否可能).
我的代码是这样的:
# All chunkFuncs keys are class definitions, all values are functions
chunkFuncs = {Math_EXP : Math_EXPChunk, Assignment : AssignmentChunk, Function : FunctionChunk}
def Chunker(chunk, localScope):
for chunkType in chunkFuncs:
if isinstance(chunk,chunkType):
# The next line is where the error is raised
localScope = chunkFuncs[chunk](chunk,localScope)
return localScope
Run Code Online (Sandbox Code Playgroud)
而错误就是这个
TypeError: unhashable type: 'Assignment'
Run Code Online (Sandbox Code Playgroud)
以下是类定义:
class Math_EXP(pyPeg.List):
grammar = [Number,Symbol],pyPeg.maybe_some(Math_OP,[Number,Symbol])
class Assignment(pyPeg.List):
grammar = Symbol,'=',[Math_EXP,Number]
class Function(pyPeg.List):
grammar = Symbol,'(',pyPeg.optional(pyPeg.csl([Symbol,Number])),')'
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以用来获得相同的效果?
谢谢.