相关疑难解决方法(0)

如何测试函数的平等性或身份?

我希望能够测试两个可调用对象是否相同.我更喜欢身份语义(使用"是"运算符),但我发现当涉及方法时,会发生不同的事情.

#(1) identity and equality with a method
class Foo(object):
    def bar(self):
        pass
foo = Foo()
b = foo.bar
b == foo.bar    #evaluates True. why?
b is foo.bar    #evaluates False. why?
Run Code Online (Sandbox Code Playgroud)

我用Python 2.7和3.3(CPython)重现了这一点,以确保它不是旧版本的实现细节.在其他情况下,身份测试按预期工作(翻译会议从上面继续):

#(2) with a non-method function
def fun(self):
    pass
f = fun
f == fun    #evaluates True
f is fun    #evaluates True

#(3) when fun is bound as a method 
Foo.met = fun
foo.met == fun    #evaluates False
foo.met is fun    #evaluates False

#(4) with a callable data …
Run Code Online (Sandbox Code Playgroud)

python

17
推荐指数
1
解决办法
794
查看次数

为什么方法没有引用相等?

我有一个错误,我在使用时依赖于彼此相等的方法is.事实证明并非如此:

>>> class What(object):
    def meth(self):
        pass

>>> What.meth is What.meth
False
>>> inst = What()
>>> inst.meth is inst.meth
False
Run Code Online (Sandbox Code Playgroud)

为什么会这样?它适用于常规功能:

>>> def func():
    pass

>>> func is func
True
Run Code Online (Sandbox Code Playgroud)

python methods identity equality reference

14
推荐指数
1
解决办法
821
查看次数

标签 统计

python ×2

equality ×1

identity ×1

methods ×1

reference ×1