In this Python oops program, we will create a Python class with class method. The program demonstrates the usage of a Python class with class method. The class_method
is defined within the MyClass
class and can be called directly on the class itself. It accesses and prints the value of the class variable class_var
.
Python class with class method
Steps to solve the program
- The code demonstrates the usage of a class method within a class in Python.
- Class methods are defined using the @classmethod decorator before the method definition. They receive the class itself as the first parameter, conventionally named cls. Class methods are commonly used when the method needs to access or modify class-level variables or perform some operation specific to the class itself.
- In this case, the class_method() is a method that prints the value of the class_var class variable when called. The class variable can be accessed using cls.class_var, where cls refers to the class itself.
- To invoke a class method, we use the class name followed by the method name, like MyClass.class_method(). Since class methods are associated with the class itself, they can be called without creating an object of the class.
- Class methods are useful when you want to define methods that are related to the class as a whole and not specific to any particular instance. They can access class variables and perform operations that affect the class itself.
class MyClass:
class_var = "Hello"
@classmethod
def class_method(cls):
print("Class variable:", cls.class_var)
MyClass.class_method()
Output:
Class variable: Hello