Python Class Method with Examples

Posted in

Python Class Method with Examples
vinaykhatri

Vinay Khatri
Last updated on October 6, 2024

    In a Python Class, we can define 3 types of methods.

    1. Instance Method

    These methods' first parameter value is reserved with the conventional name self . The name self represents the object or the instance that is calling that method. Instance methods are generally used to create, access, and modify instances variables of the class.

    Example

    class A:
        #instance method 
        def instance_method(self):
            pass

    2. Class Method

    Class methods are the special methods in the Python class that are used to deal with the class variables only. To create a class method we use the @classmethod decorator and the first parameter of these methods is conventionally named as cls .

    class A:
        @classmethod
        def class_method(cls):
            pass

    3. Static Method

    Static methods are the normal functions defined inside the class. These methods are used when the method is supposed to do some static work and does not require class and instance variables. That’s why static methods do not accept any cls and self parameter.

    Example

    class A:
        #static method 
        def static_method():
            pass

    All these three methods are used while working with a class in Python. In this Python tutorial, we will discuss the Class method in detail with the help of some examples. And by the end of this tutorial, you will have a solid grasp of the following topics.

    • What is Class Method in Python
    • How to create class method using @classmethod decorator.
    • How to create class method using classmethod() function.
    • How to access class variables in Class Methods.
    • How Class Method works with inheritance
    • How to dynamically add a class method to a class
    • How to delete a class method?

    So let’s get started,

    What is class method Python?

    Class methods in Python are the methods that are called by the class itself, unlike instance methods class methods are not object-specific. These methods are used when we want to perform some operation on the class instead of a particular object. Class methods are generally used to create, access, and modify the class variables.

    Key Points about class methods

    • Class methods are bounded to the class, not to the objects of the class.
    • The class methods are shared by all the objects.

    If a class has class variables, then we should define the class methods in the class to work with those class variables. The class method first parameter is reserved by the cls name representing the class itself.

    Defining the Class Method

    Defining a class method is similar to defining a normal or instance method in Class. In order to tell Python the method is a class method we explicitly have to provide some syntax to the method to distinguish it from the normal instance method. In the normal instance method, we use the self keyword as the first parameter, but in the class method, we use the cls as the first parameter.

    Note: self and cls are the conventional names, you can name them anything. If both the names are conventional that’s why we explicitly need to specify some syntax to the method so Python treats it as a class method, not an Instance or a normal method.

    Key Points about defining a Class method in Python

    • The class method’s first parameter conventional name is cls .
    • The cls represent the class itself.

    Enough about the theory of the class methods let’s discuss how to define a class method. There are two ways to define a class method, using the @classmethod decorator or classmethod() function.

    Create a class method using @classmethod decorator

    The easiest and more legible way to create a class method is @classmethod decorator. The @classmethod is an inbuilt Python decorator, and it is used to create classmethod inside the class body.

    Syntax

    class ClassName:
        @classmethod
        def class_method_name(cls):
            #class method body

    Example

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
        #class method
        @classmethod
        def show_company_name(cls):
            #access class variable using class
            return cls.company_name
    
        @classmethod
        def change_company_name(cls, new_name):
            cls.company_name = new_name
    
    e1= Employee("TGB01", "Jay")
    e2 = Employee("TGB02", 'Raj')
    
    #employee company name after changing
    print("e1 company name: ",e1.show_company_name())
    print("e2 company name: ",e2.show_company_name())
    
    #change the company name using class method with one object
    e1.change_company_name("TechGeekBuzz Pvt. LTD")
    
    #employee company name after changing
    print("e1 company name: ",e1.show_company_name())
    print("e2 company name: ",e2.show_company_name())

    Output

    e1 company name:  TechGeekBuzz
    e2 company name:  TechGeekBuzz
    e1 company name:  TechGeekBuzz Pvt. LTD
    e2 company name:  TechGeekBuzz Pvt. LTD

    In this example you can see that we called the classmethod change_company_name() on e1 object and it change the company name for both the objects, because company_name is the class variable and shared by both objects e1 , and e2 . The statement in the class method cls.company_name = new_name is equivalent to Employee.company_name = new_name

    Create a class method using classmethod() function

    Another way to create a class method is by using classmethod() function. The classmethod() function is an inbuilt Python function that can convert a normal method to a class method, and return it.

    Syntax

    Class_name.function = classmethod(Class_name.function)

    function is the method defined in the class that we want to convert into class method.

    Note: The method that we want to convert into class method must have a cls as a first parameter value.

    Example

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
        #normal method
        def show_company_name(cls):
            #access class variable using class
            return cls.company_name
    
        #normal method
        def change_company_name(cls, new_name):
            cls.company_name = new_name
    
    e1= Employee("TGB01", "Jay")
    e2 = Employee("TGB02", 'Raj')
    
    #employee company name after changing
    print("e1 company name: ",e1.show_company_name())
    print("e2 company name: ",e2.show_company_name())
    
    #convert the show_company_name and  change_company_name methods to class method
    Employee.show_company_name = classmethod(Employee.show_company_name)
    Employee.change_company_name = classmethod(Employee.change_company_name)
    
    #call the change_company_name class method
    Employee.change_company_name("TechGeekBuzz PVT LTD.")
    
    #employee company name after changing
    print("e1 company name: ",e1.show_company_name())
    print("e2 company name: ",e2.show_company_name())

    Output

    e1 company name:  TechGeekBuzz
    e2 company name:  TechGeekBuzz
    e1 company name:  TechGeekBuzz PVT LTD.
    e2 company name:  TechGeekBuzz PVT LTD.

    Note : When we want to use the class method in Python it is always suggested to use the @classmethod decorator instead of classmethod() function because it increases the code readability, and distinct the class method in the class body only.

    How the class method works with Inheritance

    In Python inheritance , the child class inherits all the properties of its parent class including attributes and methods. And the class methods are no exceptions. If a parent class has a class method, the child class will also be able to access that method.

    Example

    class Parent:
        home_location = "New York"
    
        @classmethod
        def show_location(cls):
            return cls.home_location
    
    class Child(Parent):
        def __init__(self, name):
            self.name = name
    
    c1 = Child("Raj")
    
    #access the class method of parent class
    print(c1.show_location())

    Output

    New York

    How to add a class method to a class Dynamically?

    Generally, we define the class method inside a class body. As Python is a dynamically typed programming language it allows us to define a class method to a class outside the class body. Defining a class method outside the class is not that recommended because class methods are associated with the class, and it affects all the objects of the class. Still, we can define a classmethod outside the class when we want to extend the functionality of the class without changing the basic structure. The only way to define a class method outside the class is the classmethod() function.

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
    #Python normal function
    def change_company_name(cls, new_name):
            cls.company_name = new_name
    
    #normal method
    def show_company_name(cls):
        #access class variable using class
        return cls.company_name                        
    
    
    e1= Employee("TGB01", "Jay")
    e2 = Employee("TGB02", 'Raj')
    
    #add the new class method to the class Employee
    Employee.show_company_name = classmethod(show_company_name)
    Employee.change_company_name = classmethod(change_company_name)
    
    #call the change_company_name class method on e1 object
    e1.change_company_name("TechGeekBuzz PVT LTD")
    
    #employee company name after changing
    print("e1 company name: ",e1.show_company_name())
    print("e2 company name: ",e2.show_company_name())

    Output

    e1 company name:  TechGeekBuzz PVT LTD
    e2 company name:  TechGeekBuzz PVT LTD

    In this example you can see that we have added two new class methods to the Employee class, using classmethod() function. You can also notice that we have only called the change_company_name () method on e1 object but it change the company name to e2 as well. This is because company_name is the class variable and its value is shared between the objects. That’s why adding a new classmethod dynamically is not recommended because if you try to modify the class variables or access the class method with one object it will reflect the changes in other objects.

    How to delete the class method dynamically?

    In Python to delete a class method from a class we can either use the del keyword or the delattr () function.

    Delete the class method using del keyword

    The del keyword in Python is used to delete objects, as in Python everything is an object we can use the del keyword to delete the classmethod.

    Example

    class Employee:
        #class variable
        company_name = "TechGeekBuzz"
    
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
        #Python classmethod
        @classmethod
        def change_company_name(cls, new_name):
                cls.company_name = new_name
    
    e1= Employee("ET01","Rohan")
    
    #call the class method before deleting
    Employee.change_company_name("TechGeekBuzz PVT LTD")
    
    #access the company name
    print(Employee.company_name)
    
    #delete the class method change_company_name
    del Employee.change_company_name
    
    #ERROR
    #call the class method after deleting
    Employee.change_company_name("TechGeekBuzz PVT LTD")

    Output

    TechGeekBuzz PVT LTD
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 29, in <module>
        Employee.change_company_name("TechGeekBuzz PVT LTD")
    AttributeError: type object 'Employee' has no attribute 'change_company_name'

    Delete the class method using delattr() function

    delattr() is a built-in function of Python, it can also use to delete the classmethod from a class.

    Example

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        def __init__(self, id, name):
            self.id = id
            self.name = name
    
        #Python classmethod
        @classmethod
        def change_company_name(cls, new_name):
                cls.company_name = new_name
    
    e1= Employee("ET01","Rohan")
    
    #call the class method before deleting
    Employee.change_company_name("TechGeekBuzz PVT LTD")
    
    #access the company name
    print(Employee.company_name)
    
    #delete the class method change_company_name
    delattr(Employee, 'change_company_name')
    
    #ERROR
    #call the class method after deleting
    Employee.change_company_name("TechGeekBuzz PVT LTD")

    Output

    TechGeekBuzz PVT LTD
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 28, in <module>
        Employee.change_company_name("TechGeekBuzz PVT LTD")
    AttributeError: type object 'Employee' has no attribute 'change_company_name'

    When to use the class methods in Python

    Create Factory Methods

    Python does not support function overloading, instead, it supports the concept of Factory Method. A Factory method is a method that returns a class object, which means using a factory method we can create a new object of the same class.

    Example

    class Iphone:
        model = "13 mini"
    
        def __init__(self,country, price, currency):
            self.country = country
            self.price = price
            self.currency = currency
    
        @classmethod
        def available(cls, country,price, currency):
            #return a new class object
            return cls( country, price, currency)
    
        def show(self):
            print(f"Iphone {self.model} price in {self.country} is {self.price} {self.currency}")
    
    iphoneUSA = Iphone("USA", 699, "$")
    iphoneUSA.show()
    
    #iphone 13 mini in india based on the iphoneUSA
    iphoneIndia = iphoneUSA.available('India', 51382, 'Rs')
    iphoneIndia.show()

    Output

    Iphone 13 mini price in USA is 699 $
    Iphone 13 mini price in India is 51382 Rs

    In the above example, the available() is a class method that returns a new instance of the cls , which makes the available() a factory method. Returning cls( country, price, currency) in available() method is equivalent to Iphone( country, price, currency) .

    Conclusion

    In this Python tutorial, we discussed what are class methods in python and how to define them. Class methods are similar to the normal methods, the difference is, in normal methods we use the self parameter which represents the object that is calling that method. But in class method, we use the cls parameter that represents the class itself. To define a class method we can either use the @classmethod decorator or the classmethod() function. We also learn how to create and delete the class method dynamically using the classmethod function and del or delattr().

    People are also reading:

    Leave a Comment on this Post

    0 Comments