Menu Close

Python classmethod() function

python classmethod function

In this article, you will learn all about the Python classmethod along with an example. A Python classmethod is a Python built-in function that comes with Python by default it is written inside the class and takes cls as a first parameter implicitly.

To understand classmethod() function, At least you should have knowledge about Object-Oriented Programming. You can learn Python Object-oriented programming by clicking here.

In this guide, we will see a total of two ways to define classmethod in Python.
Two ways are:-

  • Using classmethod() function
  • Using @classmethod Decorator

Python classmethod() function Introduction

the class method in Python is a way to define a method for the Python class. When we create the Python classmethod, The first argument of the class method is implicitly cls which represents the class name itself.

A class method is always bound to the class itself not object to that class and it does not require creating an instance or object of the class. A class method can be called from both class and object.

You have to remember some points when you are working with classmethod.

  • A Python class method is a method that is bound to the class not the object of that class.
  • They have to access the state of the class, it takes cls as the first argument that points to the class name do not object to that class.
  • It can modify the state of the class that applies to all the instances of the class.

In Python, classmethod() is a part of Python built-in functions that return a class method for a given function.

Syntax

classmethod(function)

Parameter

classmethod() takes a single parameter.

function:- A Python function to be converted to a class method.

Return Type

classmethod() returns the class method for a given function

Creating class method using classmethod()

As we have discussed earlier, Python provides two ways to create class methods. classmethod() function and @classmethod decorator. Let’s discuss these two ways only by one with the help of the example.

Example: Creating class method using classmethod()

In this example, I am gonna create a class method with the help of the classmethod() built-in function.


class Person:
    name = "Programming Funda"

    def printName(cls):
        print('My name is :- ', cls.name)


# call classmethod using class name
Person.printName = classmethod(Person.printName)
Person.printName()

Output

My name is :-  Programming Funda

In the above example, we have a class Person along with the member variable name. We also have a function name printName which takes cls as a first parameter and prints the value of the name member variable. You have to keep a point in mind here, cls represent the class name such as Person not an object/instance of the Person class.

Now, we have passed the Person.printName as a parameter to the classmethod() function. This function converts it into the class method and passes the class Person as a first parameter to the printName class method.

Now, we have called the printName() class method by using the class name Person not object of that class.

Creating class method using @classmethod decorator

This is the second way to create class methods in Python and this is a popular one also. You just need to use @classmethod above the class method. You have to remember one thing a class method always takes cls as a first parameter.

Syntax of @classmethod


@classmethod
def func(cls, arg.....)

Example:- Create class method using @classmethod


class Person:
	city = 'Delhi'
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	@classmethod
	def cityName(cls):
		print(cls.city)
		
	def printDetails(self):
		print(f"My name is {self.name} and my age is {self.age}")
					
obj = Person('Vishvajit', 20)
obj.printDetails()

# call class method using class name
Person.cityName()

print("---------------")

obj1 = Person('John', 30)
obj1.printDetails()

# call class method using object
obj1.cityName()

Output

My name is Vishvajit and my age is 20
Delhi
---------------
My name is John and my age is 30
Delhi

In the above example, We have a class Person having a member variable city and methods cityName and printDetails. cityName method is responsible for printing the city and printDetails is responsible for printing the details of the Person.
You have to remember one thing here, the city will be the same for all the instances or objects of the class because it member of the class not an object.

We have made cityName is the class method by using the @classmethod decorator and as you can see it takes cls as the first argument which represents the class itself ( such as Person ).

In the print section, we have created an object obj of the class Person and called printDetails() method by using obj but we have called the cityName method by using the class itself means Person.

Now, we have created another object obj1 and called the same printDetails method to print the details of the Person and this time we have called the class method by using the obj1 name not using the class name.

Points to be remembered in the above example:

  • The city is a member of the class itself not a member of the object/instance.
  • cityName is the class method because it takes cls as the first argument.
  • cls always represents the class name, In the above example, cls represents the Person.
  • printDetails is an instance method because it is associated with the object or instance of the class.

Difference between a static method and a class method

Static MethodClass Method
The static method does not take any arguments implicitly.The Class method takes cls as a first argument implicitly.
Python static method does not know anything about class it only deals with parameters.The Class method is bound to the class.
The static method is only bound to the class but not to the object.The Class method is able to change the state of the class that applies to all the class’s instances.
The static method creates using @staticmethod a decorator and staticmethod().The Class method can be called using the class name and object.
A static method can be called from both class and object.The Class method creates using @classmethod and classmethod().

Conclusion

In this article, you have learned all about the Python classmethod() function along with examples. Here we have seen totals two ways to create a class method, You can go with anyone at your convenience. From my point of view, I would recommend, always going with @classmethod decorator because it is a more easy way to create a class method.

Points that you should have while working with the class method.

  • A class method always takes cls as the first parameter.
  • cls represent the class name.
  • A class method is always bound to the class itself not the object/instance of the class.
  • It does not require creating an object of the class to call it.
  • A class method can be called with both the class name and the object of the class.

If you like this article, please share and continue for further Python tutorials.

Python built-in functions


For more information:- Click Here

Thanks for your valuable time…

Python str() function
Python round() function

Related Posts