Here is a post on static methods. In summary:
- instance methods: require the instance as the first argument
- class methods: require the class as the first argument
- static methods: require neither as the first argument
Examples
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 args:", 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
Notes
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
self
as the first argument.
- Similarly, if you need to access a class, use a class method.
- If access to neither an instance nor class is important, you can use a static method.
In the example above, the same argument is passed for each method type, but access to instance and class attributes differ through self
and cls
respectively.
Note, there is a way to access class components from an instance method by using self.__class__
, thereby obviating the need for a class method:
...
def instance_mthd2(self, val):
print("Instance method, with class access via `self`:", self.__class__.weight*val)
...
a.instance_mthd2(2)
# Instance method, with class access via `self`: 400
Regarding your questions:
- Yes. While the variable name
self
is a convention, it pertains to the instance.
- Static methods can be used to group similar utility methods under the same class.
- For methods within a class, you either need to add
self
as the first argument or decorate the method with @staticmethod
. "Non-decorated methods" without arguments will raise an error.
See Also
- R. Hettinger's talk Python's Class Development Toolkit - explains the purpose for each method type clearly with examples.