Advanced Lesson 3
Advanced Object-Oriented Programming
Chapter 4: Class attributes and methods
Static methods
To further complicate things, Python also offers a static method. This basically acts like a normal function, except that it is defined inside the scope of a class. Note that there is no compulsory first parameter self
or cls
here - it’s just a normal function! Like a class method, use a @staticmethod
decorator to make a method static; this tells Python not to pass self
or cls
as the first argument in the method call.
1 2 3 4 5 6 7 8 9 10 11 |
|
So, when you have a method that does not need any information from either cls
or self
, but can still be part of the class, then this could be a static method instead.
In my personal opinion, there is really not too many uses for static methods. Honestly, I struggled to come up with the example above, and it’s still not convincing! The only reason to use it is to group related functions inside the scope of a class. For example, you can have a Calculation
class that has static methods like sum()
, product()
, exp()
etc. In any case, it is enough that you know that @staticmethod
exists!