1

for start, let's define a class and instance of the class

class c:
    @classmethod
    def m(cls, a):
        return a + 1
a = c()

those methods are used the same way

>>> c.m(5), a.m(5)
6, 6

and cls in both cases is c

but c.m is a.m is False and c.m == a.m is True

why is the class method called by instance and class not the same and why am I able to call it even by an instance of that class

it would make sense if cls were not the same in both cases

EDIT:

I already knew the difference between is and ==

I was already successfully using is to check if two classes are the same (type(a) is int for example), but I did learn I should use it for is None, so thanks anyway for leading me to that page

My question actually was why are they not the same object

they even have same ID id(a.m) == id(c.m)

Superior
  • 787
  • 3
  • 17
  • You used the wrong operator to test for equality. They're indeed the same, just different copies of the same thing. – cs95 Jun 23 '18 at 18:21
  • Related: [Does this already answer your question?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python) – lucidbrot Jun 23 '18 at 18:22
  • 2
    It's not clear to me that this is an issue of confusion between `is` and `==`. The OP is using both so seems to know they are different. The question is *why* they are different when the two objects seem to give the same behavior. – BrenBarn Jun 23 '18 at 18:25
  • "they even have same ID" - [no they don't](https://stackoverflow.com/questions/3877230/why-does-id-id-and-id-id-in-cpython). – user2357112 Jun 26 '18 at 20:00
  • @user2357112 "they even have same ID" yes they do. I double checked: I recreated exactly the same class with same names and it is the same. try doing `id(a.m), id(c.m)` and see what comes out – Superior Jun 26 '18 at 20:07
  • The `a.m` and `c.m` you were dealing with in `a.m is c.m` didn't have the same IDs. The `a.m` and `c.m` in `id(a.m) == id(c.m)` had equal IDs, but those were different objects from the ones in the `is` comparison. – user2357112 Jun 26 '18 at 20:12
  • @user2357112 why would they be different objects from ones in `is` – Superior Jun 26 '18 at 20:15
  • Accessing a method creates a new method object. – user2357112 Jun 26 '18 at 20:18
  • @user2357112 I accessed method object in both cases. Can you explain more thoroughly what you meant – Superior Jun 27 '18 at 16:18
  • @Superior: An expression like `obj.meth` creates a new method object *every time* you evaluate the expression. – BrenBarn Jun 27 '18 at 23:19

0 Answers0