Shahrooz Jafari Shahrooz Jafari - 1 year ago 62
Python Question

Why does the 'is' operator say these methods aren't the same?

Consider this code:

class Person(object):
def sayHello(self):
return 'Hello'

print(Person().sayHello is Person().sayHello)

I would expect it to show True. Why does it show False?

Answer Source

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>>

Note: All we have in Python is runtime; there is no such thing as a separate compile time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download