To call the method of a normal class, create an object and call it. Or, I think you can call it directly with @classmethod or @staticmethod.
But as the title says, I could call it directly.
Python 3.8.2
Let's prepare a simple sample. In the code below, @staticmethod is not added, but the foo () method can be called directly.
>>> class A:
...     def foo():         # @static method not attached
...         print('Hello foo')
...
>>> A.foo()
Hello foo       <===I can call you directly for some reason
>>> A().foo()
Traceback (most recent call last):   <===Cannot be called from an object
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 0 positional arguments but 1 was given
>>>
Now let's put it on. Of course you can call it directly because it has @staticmethod attached, but you can also call it from an object.
>>> class B:
...     @staticmethod      # @attach static method
...     def foo():
...         print('Hello foo')
...
>>> B.foo()
Hello foo
>>> B().foo()
Hello foo       <===Can also be called from an object
>>>
As you can see above, it seems that there is only ** whether it can be called from an object **, but I'm not sure.
Until very recently, I didn't know that python3 had such a specification. However, it is easier to understand if you add @staticmethod, so I will continue to add it.
Let's see how it was in Python2
Python 2.7.16
>>> class A:
...     def foo():               # @static method not attached
...         print('Hello foo')
... 
>>> A.foo()
Traceback (most recent call last):   <===Do not call directly
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with A instance as first argument (got nothing instead)
>>> A().foo()
Traceback (most recent call last):    <===Of course not from the object
  File "<stdin>", line 1, in <module>
TypeError: foo() takes no arguments (1 given)
>>>
>>>
>>> class B:
...     @staticmethod             # @attach static method
...     def foo():
...         print('Hello foo')
... 
>>> B.foo()
Hello foo           <=== @staticmethod can be called
>>> B().foo()
Hello foo
>>>
Looking at this, Python 2 is no good. But why did Python 3 become OK? concern.
https://stackoverflow.com/questions/43587044/do-we-really-need-staticmethod-decorator-in-python-to-declare-static-method https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod
Recommended Posts