Class method vs Static method in Python
Class methodA class method receives the class as implicit first argument, just like an instance method receives the instance. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved.
To declare a class method:
class MyClass: @classmethod def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator.
Static methodA staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is very similar to a module level function. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
- Python does not have to instantiate a bound-method for object.
- It eases the readability of the code, and it does not depend on the state of object itself.
To declare a static method:
class MyClass: @staticmethod def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator.
Class Method Vs. Static Method
- The class method takes cls (class) as first argument while the static method does not take any specific parameter.
- Class method can access and modify the class state whereas Static Method cannot access or modify the class state.
- The class method takes the class as parameter to know about the state of that class, but static methods do not know about class state. These methods are used to do some utility tasks by taking some parameters.
- @classmethod decorator is used in Class Method and @staticmethod decorator is used in Static Method.
- How to use Date and Time in Python
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python