When we define a method using @classmethod decorator inside a class, it is called class method in Python. This method is independent of any specific instance of the class.
A class method is related to class rather than instances created of the class. Therefore, it is called on the class itself and not on an instance of the class.
Class methods offer a way to access and modify class-level data attributes and behavior. They are handy in scenarios where we need to perform operations related to the class as a whole, rather than a specific instance of class.
Class Method Definition Syntax in Python
To define a class method, we’ll need to use the @classmethod decorator followed by a method definition within the class. The general syntax to define a class method inside a class is as follows:
class MyClass: @classmethod def my_class_method(cls, parameter1, parameter2, ...): # Class method logic here
In the above syntax,
(a) @classmethod: A name used with (@) sign is called a decorator that indicates that the following method is a class method in Python. It gives the information about the code element.
(b) my_class_method: It is the name of class method which you can replace it with your desired name of class method.
(c) cls: Instead of a self keyword, a class method conventionally receives cls (short for class) as the first parameter or argument. The parameter cls refers to the class object itself. We can use any valid variable name here, but it’s a common practice to use “cls” for clarity. We can access class-level data attributes using the cls parameter in a class method.
(d) parameter1, parameter2, …: These are optional parameters that our class method header can accept. We can define any number of parameters as needed for our specific use.
Access Class Method in Python
We can access or call a class method using the class name instead of creating an object of class. The general syntax to call a class method in Python is as:
class_name.method_name()
Let’s take a simple example program in which we will access and call the class method using the name of class.
Example 1:
class MyClass: @classmethod def my_class_method(cls): print("I am class method in Python") # Outside the class definition. # Accessing and calling class method using the name of class. MyClass.my_class_method()
Output: I am class method in Python
Class Method with Parameters
Class methods can also accept parameters, just like regular methods. Parameters in method definition act as local variables within the scope of that method. Here’s an example:
Example 2:
class MyClass: @classmethod def greet(cls, name): return f"Hello, {name}!" # Outside the class definition. message = MyClass.greet("Alice") print(message)
Output: Hello, Alice!
Example 3:
class MyClass: @classmethod def sum(cls, x, y): # Perform addition operation with the parameters. result = x + y return result # Outside the class definition. # Call the class method with parameters result = MyClass.sum(10, 20) # Print the result. print("Result:", result)
Output: Result: 30
In this example, we have defined a class named MyClass, containing a sum() class method that takes two parameters x and y with cls parameter. Both parameters x and y are local variables inside the class method.
In the class method, we have performed an addition operation on the parameters x and y. Then, we have called sum() method using the name of class by passing argument values. The sum() method calculates the sum of 10 and 20 (which is 30) and returns that value. We have stored the returned result in the result variable and then printed it.
Accessing Class Variable in Class Method
In a class method in Python, we can access class variables (or static variables) by using the cls parameter, which refers to the class itself. Let’s take an example program in which we will see how to access a class variable within a class method.
Example 4:
class MyClass: class_variable = 0 # This is a class-level variable. @classmethod def increment(cls): cls.class_variable += 1 # Accessing class variable inside the class method. # Outside the class definition. # Access the class variable using the class name. print("Class Variable (Before Increment):", MyClass.class_variable) # Call the class method to increment the class variable. MyClass.increment() # Access the class variable again after incrementing. print("Class Variable (After Increment):", MyClass.class_variable)
Output: Class Variable (Before Increment): 0 Class Variable (After Increment): 1
In this example, we have defined a class named MyClass, containing a class variable named class_variable initialized to 0. Inside the class method, we have defined a increment() class method in which we have accessed and modified the value of class variable using cls.
Before calling the increment() method, we have accessed the class variable using MyClass.class_variable to print its value outside the class definition. Then, we have called the class method using the class name.
After calling increment(), the class variable is incremented by 1. We have accessed the class variable again to see the updated value outside of class definition. Remember that the cls parameter allows us to access class-level data attributes within a class method.
Can We Access Instance Variable in Class Method?
Yes, we can access instance variables in a class method, but to do so, you’ll need to have access to an instance of the class. There are two ways to access instance variables inside a class method in Python.
(a) Using an Instance Parameter: Pass an instance of the class as a parameter to the class method definition. By convention, this parameter is often named self. With the instance parameter, we can access instance variables like we would in a regular method.
However, we cannot access instance variables directly inside a class method without passing an instance of the class as a parameter. In Python, class methods are bound to the class itself, not to any particular instance.
Therefore, they don’t have access to instance variables unless we explicitly passed an instance as an argument. Let’s take an example based on the accessing instance variable within a class method.
Example 5:
class Student: # Constructor definition. def __init__(self, name, age): self.name = name self.age = age @classmethod def student_info(cls, self): print(f"Student Name: {self.name}") print(f"Student Age: {self.age}") # Create instances of the Student class student1 = Student("Alice", 20) student2 = Student("Bob", 22) # Call the class method with different instances Student.student_info(student1) Student.student_info(student2)
Output: Student Name: Alice Student Age: 20 Student Name: Bob Student Age: 22
In this example, we have defined a Student class with a class method that prints the name and age of a student. We have created two instances of the class and called the class method with each instance.
(b) Using the Class Method: We can create an instance of the class within the class method and then access its instance variables.
Example 6:
class Employee: # Constructor definition. def __init__(self, name, salary): self.name = name self.salary = salary @classmethod def employee_info(cls, name, salary): instance = cls(name, salary) # Here, instance variable represents self. print(f"Employee Name: {instance.name}") print(f"Employee Salary: {instance.salary}") # Call the class method using class name and pass instance data. Employee.employee_info("John", 50000) Employee.employee_info("Emily", 60000)
Output: Employee Name: John Employee Salary: 50000 Employee Name: Emily Employee Salary: 60000
In this example, we have defined an Employee class with a class method that creates an instance of the class within the class method. We then accessed and printed the name and salary of the employee.
These examples demonstrate two approaches to accessing instance variables within a class method. The choice between them depends on your specific use case.
Always remember that if you want to access instance variables within a class method, you should either pass an object as a parameter to the class method definition or create an object within the class method, as demonstrated in the previous examples.
Calling Instance Method within Class Method in Python
To call an instance method within the class method in Python, we will use the same approach as discussed in the previous section. Let’s understand it with the help of some examples.
Example 7:
class MyClass: def instance_method(self): print("This is an instance method.") @classmethod def class_method(cls): print("This is a class method.") # Create an instance of the class. instance = cls() # cls refers to the class itself. # Above statement is same as the below statement. # instance = MyClass() # Call the instance method on the created instance instance.instance_method() # Call the class method to invoke the instance method MyClass.class_method()
Output: This is a class method. This is an instance method.
To call an instance method within a class method in Python, we need to create an instance of the class and then invoke the instance method on that instance inside the class method. Since class methods are bound to the class itself, therefore, we don’t have access to instance-specific data or methods directly.
In this example, we have defined an instance method instance_method() within the MyClass class. We have defined a class method class_method() within the same class.
Inside the class_method(), we have created an instance of the class using cls(). This creates an instance of the class that we can work with. The statement instance = cls() is the same as the statement instance = MyClass().
We then called the instance method instance_method() on the created instance. This allows us to execute the instance-specific functionality from within a class method. When we called class_method(), it prints “This is a class method.” on the console and then creates an instance to call the instance method, printing in “This is an instance method.”.
Example 8:
class MyClass: def instance_method(self): print("This is an instance method.") @classmethod def class_method(cls, instance): # Here, instance refers to the current instance of class. print("This is a class method.") # Call the instance method on the provided instance instance.instance_method() # Create an instance of the class my_instance = MyClass() # Call the class method and pass the instance as an argument MyClass.class_method(my_instance)
Output: This is a class method. This is an instance method.
This is another way to call an instance method within a class method in Python. In this method, we first create an instance of the class outside the class definition and then passing that instance as an argument to the class method when calling it.
In this example, we have defined an instance method instance_method() within the MyClass class. Then, we have defined a class method class_method() within the same class, that takes an additional argument instance (or self), which refers to an instance of the class.
Outside of the class definition, we have created an instance of the class. We then call class_method() method by passing the instance my_instance as an argument. Inside the class method, we have access and called instance_method() method on the current instance using instance parameter.
Difference between Instance Method and Class Method
There are the following difference between an instance method and class method in Python. They are as:
Instance Method:
- Instance methods are bound to instances of a class.
- When we define an instance method in a class, it takes self as its first parameter, which refers to the instance of the class itself.
- We call an instance method on an instance of a class. For example: my_instance.instance_method().
- Instance method allows us to access and modify instance-level data attributes.
Class Method:
- Class methods are bound to the class itself, rather than instances of the class.
- When we define a class method, it takes cls as its first parameter, which refers to the class.
- We call a class method on the class itself, not on an instance of the class. For example: MyClass.class_method()
- Class method allows us to access and modify class-level data attributes.
Question1: Is it possible to call a class method on an instance of the class?
Answer: Yes, we can call a class method on both the class itself and an instance of the class. However, conventionally, class methods are called using the name of class.
In this tutorial, we have explained class method in Python with the help of various important example programs. Hope that you will have understood the basic definition and syntax of class method and practiced all programs.
Thanks for reading!!!