Here is the post in static methods . In short:
- instance methods: requires the instance to be the first argument
- class methods: the class is required to be the first argument
- static methods: not required as first argument
Regarding your questions:
- Yes. Although the variable name
self is conditional, it refers to an instance. - Static methods can be used to group similar utility methods in one class.
- For methods inside the class, you need to add
self as the first argument or decorate the method with @staticmethod . "Unformed methods" without arguments will cause an error.
It may be more clear how they work when called with arguments. Modified example:
class TestClass: weight = 200
In general, you can think of each method in terms of access :
- If you need to access an instance or an instance component (for example, an attribute of an instance), use the instance method since it passes
self as the first argument. - Similarly, if you need access to a class, use the class method.
- If access to neither the instance nor the class is important, you can use the static method.
Note that in the example above, the same argument is passed for each type of method, but access to the attributes of the instance and class is different via self and cls respectively.
Note: there is a way to access the components of a class from an instance method using self.__class__ , thereby eliminating 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)
REF: I recommend a look at the Raymond Hettinger talk Python Class Development Toolkit, which clearly explains the purpose of each type of method with examples.
source share