Python classmethod() Explained [Easy Examples]

 

Introduction to Python classmethod()

A Python class is like an outline for creating a new object. An object is anything that you wish to manipulate or change while working through the code. Every time a class object is instantiated, which is when we declare a variable, a new object is initiated from scratch. A class can contain different methods including instance methods, class methods, or static methods.

In this tutorial, we will learn about the python classmethod(). We will learn how we declare a classmethod() inside a python class. We will also cover the differences between the Python class method, instance method, and static method along with various examples. Moreover, we will also discuss how we can create a python class with multiple arguments by solving examples.

Advertisement

In a nutshell, this tutorial will contain all the necessary information and examples that you need to know in order to start working with the Python classmethod().

 

Getting started with Python classmethod()

A Python class method is a method that is bound to the class and not the object of the class. It has the access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class. In this section, we will learn the basic syntax of declaring the Python classmethod().

 

Method-1 Declaring Python classmethod()

The simplest way of declaring a python classmethod() is using the method classmethod() function which takes a method as a parameter and returns the python class method. The syntax looks like this:

classmethod(function_name)

The classmethod() method returns a class method for the given function. Now let us take an example and see how we can use this in our python program. See the example below:

# Python class
class welcome:
    # class variable
    Name = 'golinuxcloud'
    # python method
    def start(obj):
        print("Welcome to  : ", obj.Name)
# creating python class method using classmethod() function
welcome.start = classmethod(welcome.start)
# calling python class method
welcome.start()

Output:

Welcome to : golinuxcloud

Notice that we have used the classmethod() function in our program to convert the method inside the class into a python classmethod().

Advertisement

 

Method-2 Declaring Python classmethod()

Now let us see how we can declare a Python classmethod() using python decorators. A decorator in Python is a function that takes another function as its argument and returns yet another function. Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code. Here we will use a python decorator for a classmethod() to declare the python class method. See the syntax below:

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

Using a decorator to declare a python classmethod() is more pythonic way than using classmethod() function. Now let us take an example and see how we can use the python decorator to declare the python class method. See the example below:

# Python class
class welcome:
    # class variable
    Name = 'golinuxcloud'
    # using python decorator to delcare class method
    @classmethod
    # python method
    def start(obj):
        print("Welcome to  : ", obj.Name)
# calling python class method
welcome.start()

Output:

Welcome to : golinuxcloud

You can see that we have used the @classmethod decorator to declare a class method rather than using classmethod() function.

 

Python classmethod() inside a class

A Python class can contain many types of methods inside it. For example static, non-statice, or class methods. And they are called by different ways, for example a static method can be called without creating any new object while to call a non-static method, we have to create an object first. In similar way, we can call python classmethod() in both ways; without creating object or by creating object.

 

Method-1 Calling Python classmethod() without creating object

Now let us take an example and see how we can call a class method without creating new object. We will use the call name to call the methd. See the example below:

# Python class
class greeding:
    # class variable
    Name = "Bashir"
    # using python decorator to delcare class method
    @classmethod
    # python method
    def introduction(obj):
        print("Hello! My name is : ", obj.Name)
# calling python class method without creating object
greeding.introduction()

Output:

Hello! My name is : Bashir

Notice that we did not had created any new object, we directly call the method using the name of class. If we change the variable using the class name, it will also get changed inside our class method. For example, see the program below:

Advertisement
# Python class
class greeding:
    # class variable
    Name = "Bashir"
    # using python decorator to delcare class method
    @classmethod
    # python method
    def introduction(obj):
        print("Hello! My name is : ", obj.Name)
# changing the variable
greeding.Name = "GolinuxCloud"
# calling python class method without creating object
greeding.introduction()

Output:

Hello! My name is : GolinuxCloud

Notice that we changed the variable using the class name and it also changed inside our python class method.

 

Method-2 Calling Python classmethod() by creating an object

We can also call the class method by creating an object and by using the name of object instead of class itself. See the example below:

# Python class
class greeding:
    # class variable
    Name = "Bashir"
    # using python decorator to delcare class method
    @classmethod
    # python method
    def introduction(obj):
        print("Hello! My name is : ", obj.Name)
# creating new object of type greeding
new_object = greeding()
# calling the python class method using object name
new_object.introduction()

Output:

Hello! My name is : Bashir

Notice that we first created a new object and then using that object we called the class method. One disadvantage of this method is that if we make any changes to the object using object name, it will not appear in our class method. For example, see the program below:

# Python class
class greeding:
    # class variable
    Name = "Bashir"
    # using python decorator to delcare class method
    @classmethod
    # python method
    def introduction(obj):
        print("Hello! My name is : ", obj.Name)
# creating new object of type greeding
new_object = greeding()
# changing the Name using object 
new_object.Name = "GolincxCloud"
# calling the python class method using object name
new_object.introduction()

Output:

Hello! My name is : Bashir

Notice that although we had changed the variable name of object but still we get the previous name. It is because the classmethod() is associated with python class not with object, so any changes in object will not appear inside our classmethod().

 

Difference between Python class method and static method

A class method is a method that is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. While A static method is also a method that is bound to the class and not the object of the class. A static method can't access or modify the class state. You can learn more about static method from the article on Python static method. In this section, we will see some of the differences between the python static method and the class method. See the list below:

Advertisement
  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can not access or modify it.
  • Static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods have class as a parameter.
  • We use the @classmethod decorator in python to create a class method and we use the @staticmethod decorator to create a static method in python.

 

Python classmethod() with multiple arguments

A class method is similar to an instance method, but it has a class object passed as its first argument.  By contrast, when a class method is called from either a class object or an instance object, the class object is automatically passed as the first argument to the method. Instead of calling this first argument  self, the convention is to name it cls. We can add more arguments to our class method along with cls. See the example below, which takes multiple arguments and returns the sum.

# Python class
class addition:
    # class variable
    sum = 0
    # using python decorator to delcare class method
    @classmethod
    # python method
    def Sum(cls, num1, num2):
        # finding the sum
        cls.sum = num1 + num2
        print("The sum is : ", cls.sum)  
# calling the class method with multiple arguments
addition.Sum(10, 5)

Output:

The sum is : 15

Notice that the classmethod() in the above examples takes two more arguments along with the default one and returns the sum of the two numbers.

 

Summary

As we discussed that python class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method. In this tutorial, we learned about the Python class method. We learned different ways to declare python class methods along with various examples. We also discussed two different ways to call a class method and the difference that these methods have by showing through examples. Moreover, we covered how we can declare and call a class method with multiple arguments. To summarize, this tutorial contains all the necessary concepts and examples that are important to start working with python class methods.

 

Further Reading Section

Python class method
Python static method
Python class

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment