Lately, I've been studying Python's class instantiation process to really understand what happen under the hood when creating a class instance. But, while playing around with test code, I came across something I don't understand.
Consider this dummy class
class Foo():
def test(self):
print("I'm using test()")
Normally, if I wanted to use Foo.test instance method, I would go and create an instance of Foo and call it explicitly like so,
foo_inst = Foo()
foo_inst.test()
>>>> I'm using test()
But, I found that calling it that way ends up with the same result,
Foo.test(Foo)
>>>> I'm using test()
Here I don't actually create an instance, but I'm still accessing Foo's instance method. Why and how is this working in the context of Python ? I mean self normally refers to the current instance of the class, but I'm not technically creating a class instance in this case.
print(Foo()) #This is a Foo object
>>>><__main__.Foo object at ...>
print(Foo) #This is not
>>>> <class '__main__.Foo'>
Foo.test(None). So the argument doesn't necessarily need to be the class the method belongs to.selffor both cases and you'll see the difference.testmethod does not use theselfargument, it can be anything (or None) as shown above. What you should actually do with such a method is make it astaticmethod (does not have aselfarg).selfdoesn't need to be of the class type. Thank you all.Foois also an object and this is why it accepts it.inst = Foo():inst.test()is equivalent toFoo.test(inst)