class method and static method in python
Class method and static method in Python are special types of methods, that are defined within a class but behave differently in terms of their usage and behavior.
Class Method:
A class method is a method that is bound to the class itself rather than to instances of the class (objects). It can access and modify class-level attributes and perform operations that are related to the class as a whole. Class methods are defined using the @classmethod decorator before the method definition.
Key Characteristics of Class Methods:
>> Defined using the ‘@classmethod’ decorator.
>> The first parameter is typically named cls, which represents the class itself.
>> Can access and modify class-level attributes.
>> Can be called using either the class or an instance of the class.
>> Commonly used to create factory methods or perform operations related to the class itself.
Example of Class Methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class MyClass: class_attribute = 10 @classmethod def class_method(cls): print("Class method called") print("Class attribute:", cls.class_attribute) # Calling the class method using the class itself MyClass.class_method() # Calling the class method using an instance of the class obj = MyClass() obj.class_method() |
Static Method:
A static method is a method that does not operate on instance or class attributes. It behaves like a regular function but is defined within a class for organizational purposes. Static methods are defined using the @staticmethod decorator before the method definition.
Key Characteristics of Static Methods:
>> Defined using the ‘@staticmethod’ decorator.
>> Does not have access to instance or class attributes (no self or cls parameters).
>> Behaves like a regular function but is defined within the class namespace.
>> Can be called using either the class or an instance of the class, but does not implicitly pass the instance or class as the first parameter.
Example of Static Methods
1 2 3 4 5 6 7 8 9 10 11 | class MyClass: @staticmethod def static_method(): print("Static method called") # Calling the static method using the class itself MyClass.static_method() # Calling the static method using an instance of the class obj = MyClass() obj.static_method() |
Conclusion
>> Class methods are used to perform operations related to the class itself and have access to class-level attributes.
>> Static methods are used for utility functions that do not require access to instance or class attributes.
>> Both class methods and static methods can be called using either the class or an instance of the class, but their behavior differs in terms of access to attributes and class context.
Check out our other Python programming examples