In this Python oops program, we will create a Python class with static methods. The program demonstrates the usage of a static method in Python. The static method static_method
is defined within the MyClass
class and can be called directly on the class itself.
Python class with static methods
Steps to solve the program
- The code demonstrates the usage of a class with static methods in Python.
- Static methods are defined using the @staticmethod decorator before the method definition. They do not receive any special first parameter like self or cls. Therefore, they do not have access to the instance or class variables.
- In this case, the static_method() is a simple method that prints the string “This is a static method” when called.
- To invoke a static method, we use the class name followed by the method name, like MyClass.static_method(). Since static methods are associated with the class itself, they can be called without creating an object of the class.
- Static methods are commonly used when a method does not require access to instance or class variables, and its behavior is independent of the specific instances of the class. They provide a way to encapsulate utility or helper functions within a class.
class MyClass:
@staticmethod
def static_method():
print("This is a static method")
MyClass.static_method()
Output:
This is a static method
Related Articles
Python oops program to create a class with the class method.
Write a Python Class to get the class name and module name.
Write a Python Class object under syntax if __name__ == ‘__main__’.
Python class with Single Inheritance.
Python Class with Multiple Inheritance.
Python Class with Multilevel Inheritance.