为何对象方法引用变量与原对象方法is判断不相等?
问题解析:对象方法赋值后
is与==判断的差异 当把对象属性初始化指向对象方法后,用is判断该变量和原方法时结果为False,但==判断结果为True,这和普通函数赋值的表现不同。以下是代码示例及原因分析:
示例代码
class SomeClass: def __init__(self): self.command = self.do_something def do_stuff(self): print('c1:', id(self.command)) print('c2:', id(self.do_something)) if self.command is self.do_something: return 'Commands match (is)' elif self.command == self.do_something: return 'Commands match (==)' return 'Commands do not match at all' def do_something(self): pass some_object = SomeClass() print(some_object.do_stuff()) print() def some_func(): pass command = some_func print('c1:', id(some_func)) print('c2:', id(command)) if some_func is command: print('Commands match (is)') else: print('Commands do not match at all')
原因分析
普通函数赋值场景:
command = some_func是直接让变量command引用some_func这个函数对象本身,两者指向同一个内存地址,id相同,因此is判断返回True。对象方法赋值场景:
- 访问
self.do_something时,Python会动态创建一个绑定方法(bound method)对象,这个对象包含实例self和底层函数SomeClass.do_something。 __init__中self.command = self.do_something是把当时生成的绑定方法对象赋值给self.command。- 后续在
do_stuff中再次访问self.do_something时,Python会重新生成一个新的绑定方法对象。虽然新对象和self.command绑定的实例、底层函数都相同,但它们是两个独立的对象实例,所以id不同,is判断返回False。 - 而
==判断绑定方法时,会对比两者绑定的实例和底层函数是否一致,因此结果返回True。
- 访问
内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
相关产品推荐

