0

I was experimenting with class method in python when I stumbled upon this issue of id.

class MyClass:
    def method(self):
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        return 'static method called'

print(id(MyClass.classmethod), "MyClass")
print(id(obj1.classmethod), "obj1")
print(id(obj2.classmethod), "obj2")
print("------------------------")
print(id(MyClass.classmethod), MyClass.classmethod)
print(id(obj1.classmethod), obj1.classmethod)
print(id(obj2.classmethod), obj2.classmethod)

The output is Output

140600363181376 MyClass
140600363181568 Obj1
140600363181376 Obj2
------------------------
140600363181568 <bound method MyClass.classmethod of <class '__main__.MyClass'>>
140600363181568 <bound method MyClass.classmethod of <class '__main__.MyClass'>>
140600363181568 <bound method MyClass.classmethod of <class '__main__.MyClass'>>

Why is the id different though the same methods were called?

When using python 3.9.12 and 3.10.7, the output was similar as in above. But when using python 3.8.10, the print of all id was same.

  • ```obj1.classmethod``` is a "bound method". That's a new, temporary object – Homer512 Oct 14 '22 at 09:41
  • When I ran the code in different versions of Cpython: python 3.9.12 and 3.10.7 the print of id were similar as in the above output. However in python 3.8.10, all the print of id gave the same value. – Aayush Shah Oct 14 '22 at 11:27
  • That's simply a matter of how the memory allocator handles things. Note that you don't keep the objects alive beyond the print call. So the ID can immediately be reused. If I run ```o1, o2 = obj1.classmethod, obj1.classmethod; print(id(o1), id(o2))```, I get two different IDs. Tested with Python3.6 – Homer512 Oct 14 '22 at 20:00

0 Answers0