0
class s:
    a = 0
    
    def obj(self):
        pass
    
    @classmethod
    def cla(cls):
        pass
    
    @staticmethod
    def sta():
        pass
    
t = s()

print(t.a is s.a)
print(t.obj is s.obj)
print(t.cla is s.cla)
print(t.sta is s.sta)

print(id(t.a), id(s.a))
print(id(t.obj), id(s.obj))
print(id(t.cla), id(s.cla))
print(id(t.sta), id(s.sta))

print(id(t.a) == id(s.a))
print(id(t.obj) == id(s.obj))
print(id(t.cla) == id(s.cla))
print(id(t.sta) == id(s.sta))

In the above program, cla() is a classmethod. classmethod are created once in the class, not its object. while checking whether the address of the classmethod in class and its object are same or not. I found some strange thing.

When I see the address of the classmethod of both class and its object, they printed the same address.

print(id(t.cla), id(s.cla)) # both printed address are same 1944310966664 1944310966664

once again I check that with equal to operator on id's of both class method. it printed True.

print(id(t.cla) == id(s.cla)) # it print true

but when I try this with is operator, that print false.

print(t.cla is s.cla) # it print false

I really don't know why this happen. the is operator also check whether the both the id's are same or not. Please anyone help me in this.

Advance thanks for investing your time to clear my doubt.

  • *All* methods are attributes of the class, not the instance. The difference between the three types of methods is the implicit argument (if any) that is passed to the function, depending on whether the attribute is accessed through the class object or an instance of the class object. – chepner Jul 24 '21 at 14:02
  • You might want to take a look at the *type* of value (`type(t.cla)`, `type(t.cla)`) instead of just looking at id of each. Also, take a look at the [Descriptor HowTo guide](https://docs.python.org/3/howto/descriptor.html), which discusses how the descriptor protocol is used to make each kind of method (instance, class, and static) behave the way they do. – chepner Jul 24 '21 at 14:05
  • As all three methods are values whose type implements `__get__`, all six expressions `{s,t}.{obj,cla,sta}` produce the return value of the value's `__get__` method, rather than the value itself. (Though in some cases, `__get__` *does* just return the value.) – chepner Jul 24 '21 at 14:10

0 Answers0