Class Method Vs Static Method in Python
- Get link
- X
- Other Apps
Class Method Vs Static Method in Python
In Python, both class methods and static methods are methods that are bound to a class rather than an instance of the class, but they have different behaviors.
A class method is a method that takes the class as its first parameter instead of the instance of the class. It is defined using the @classmethod
decorator. Class methods are used when you need to access or modify class-level data or behavior, but you don't need to access or modify instance-level data. For example:
class MyClass: class_var = 0 @classmethod def class_method(cls, x): cls.class_var += x print(f"class_var = {cls.class_var}")
In the example above, we define a class method class_method()
using the @classmethod
decorator. The first parameter of the method is cls
, which refers to the class itself, not an instance of the class. Inside the method, we access the class variable class_var
using cls.class_var
, and modify its value by adding the argument x
.
We can call the class_method()
using the class name, like this:
MyClass.class_method(1) # Output: class_var = 1
@staticmethod
decorator. Static methods are used when you need to define a method that belongs to the class, but does not access any class-level or instance-level data. For example:In the example above, we define a static method static_method()
using the @staticmethod
decorator. The method does not access any class-level or instance-level data, so we don't need to pass in the class or instance as a parameter.
We can call the static_method()
using the class name or an instance of the class, like this:
MyClass.static_method(2) # Output: y = 2 obj = MyClass() obj.static_method(3) # Output: y = 3
- Get link
- X
- Other Apps
Comments