为什么“是”运算符说这些方法不相同? [英] Why does the 'is' operator say these methods aren't the same?
本文介绍了为什么“是”运算符说这些方法不相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
class Person(object):
def sayHello(self):
return 'Hello'
print(Person().sayHello is Person().sayHello)
我希望它显示为True。为什么显示为False?
I would expect it to show True. Why does it show False?
推荐答案
方法已绑定到运行时的实例。当您运行以下代码时:
Methods on are bound to instances at runtime. When you run the following code:
print(Person().sayHello is Person().sayHello)
您创建两个实例,并且每次都有不同的内存地址。
you create two instances and each time you have a different memory address.
>>> Person().sayHello
<bound method Person.sayHello of <__main__.Person object at 0x7fbe90640410>>
>>> Person().sayHello
<bound method Person.sayHello of <__main__.Person object at 0x7fbe90640490>>
注意:我们在Python中拥有的只是运行时;没有单独的编译时间。
这篇关于为什么“是”运算符说这些方法不相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文