I am trying to understand how static methods work internally. I know how to use the @staticmethod decorator, but I will avoid using it in this post to dive deeper into how static methods work and ask my questions.
From what I know about Python, if there is a class A , then calling A.foo() calls foo() without arguments, while calling A().foo() calls foo() with one argument, where this one argument is an instance of A() .
However, in the case of static methods, it seems that always foo() is called without arguments, whether we call it A.foo() or A().foo() .
Proof below:
>>> class A: ... x = 'hi' ... def foo(): ... print('hello, world') ... bar = staticmethod(foo) ... >>> A.bar() hello, world >>> A().bar() hello, world >>> A.bar <function A.foo at 0x00000000005927B8> >>> A().bar <function A.foo at 0x00000000005927B8> >>> A.bar(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes 0 positional arguments but 1 was given >>> A().bar(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes 0 positional arguments but 1 was given
So, I'm right in concluding that the staticmethod() function does some magic, so that foo() always called with 0 arguments?
If I defined my own staticmethod() in my own Python code, how would I do it? Is it even possible to define such a method from our own Python code, or can such a function be defined only as inline?
source share