In python when we declare an instance method and class method, how they work internally?
Let us consider the below piece of code:
class A:
def method1(self):
print("Hello from instance method")
@classmethod
def method2(cls):
print("Hello from class method")
A.method1() <---- 1
A.method2() <---- 2
A().method1() <---- 3
A().method2() <---- 4
In the above, all the method calls (labelled as 1, 2, 3 and 4) work fine except 1.
I am wondering how 4 can work (where we access a class method using an instance).
While we access the method2 using an instance, how the class is passed to it?
And in call 1, I get the below error:
TypeError: method1() missing 1 required positional argument: 'self'
This is really misleading; I still pass an argument (access it via the class; so the class is passed). It needs to be something else. Isn’t ?
How I understand the first call is that: the passed one is a class; not an instance of the class A. The interpreter analyses the type and throws the error. Am I correct here?