Why `is` return False for same instance method and class method but return True for staticmethod

Viewed 63

Let the code speaks for the question:

>>> class A(object):
...     a = None
...     def b(self):
...             pass
... 
>>> a = A()
>>> a.a is a.a
True
>>> a.b is a.b
False

>>> class B(object):
...     a = None
...     @staticmethod
...     def b():
...             pass
... 
>>> b = B()
>>> b.a is b.a
True
>>> b.b is b.b
True

>>> class C(object):
...     a = None
...     @classmethod
...     def b(cls):
...             pass
... 
>>> c = C()
>>> c.a is c.a
True
>>> c.b is c.b
False
1 Answers

This will bound the method to the object of class.

a.b is a.b
<bound method A.b of <__main__.A object at 0x00000294E2DA1780>>

This will address the method directly because we can call static method directly with a class name it is not necessary to create an object to call static method.

b.b is b.b
<function B.b at 0x00000294E2C49D08>

This will bound the method directly to a class. You can call that method directly with a class name without creating an object or with object.

c.b is c.b
<bound method C.b of <class '__main__.C'>>
Related