Introduction
I have a Python class that contains several methods. I want one of these methods to have a static copy, i.e. a static method with the same name that can handle more arguments. After some searching, I found that I can use the @staticmethod decorator to create a static method.
Problem
For convenience, I created a smaller test case that reproduces the problem:
class myclass: @staticmethod def foo(): return 'static method' def foo(self): return 'public method' obj = myclass() print(obj.foo()) print(myclass.foo())
I expect the above code to print the following:
public method static method
However, the code prints the following:
public method Traceback (most recent call last): File "sandbox.py", line 14, in <module> print(myclass.foo()) TypeError: foo() missing 1 required positional argument: 'self'
From this, we can only assume that the call to myclass.foo() tries to call its non-static counter without arguments (which will not work, because non-static methods always accept the self argument). This behavior is confusing to me because I expect that any call to the static method will actually call the static method.
I tested the problem in both Python 2.7 and 3.3, only to get the same error.
Questions
Why is this happening and what can I do to fix my code so that it prints:
public method static method
how would i expect?
python static class decorator
caleb531
source share