I've developed this short test/example code, in order to understand better how static methods work in Python.
def __init__(self, size):
self.size = size
print("regular instance method - with 'self'")
print("static instance method - with @staticmethod")
print("static class method")
a = TestClass(1000)
Here is a post on static methods. In summary:
Regarding your questions:
selfis a convention, it pertains to the instance.
selfas an argument or decorate the method it with
It may be more clear to see how these work when called with arguments. A modified example:
class TestClass: weight = 200 # class attr def __init__(self, size): self.size = size # instance attr def instance_mthd(self, val): print("Instance method, with 'self':", self.size*val) @classmethod def class_mthd(cls, val): print("Class method, with `cls`:", cls.weight*val) @staticmethod def static_mthd(val): print("Static method, with neither: ", val) a = TestClass(1000) a.instance_mthd(2) # Instance method, with 'self': 2000 TestClass.class_mthd(2) # Class method, with `cls`: 400 a.static_mthd(2) # Static method, with neither args: 2
Overall, you can think of each method in terms of access: if you need to access the instance or an instance component (e.g. an instance attribute), use an instance method as it passes in
self. Similarly, if you need to access a class, use a class method. If access to neither is important, you can use a static method. Notice in the example above, the same argument is passed for each method type, but access to instance and class attributes differ via
If we need to access the class within an instance method, we could use
... def instance_mthd2(self, val): print("Instance method, with `self` but class access:", self.__class__.weight*val) ... a.instance_mthd2(2) # Instance method, with `self` but class access: 400
I recommend watching Raymond Hettinger's talk Python's Class Development Toolkit, which elucidates the purpose for each method type clearly with examples.