Python Class Methods Tutorial

  • Post author:
  • Post category:Python

In this section, we will learn about class methods in Python.

What is Python Class Method?

A class method is a type of method that can be invoked only using the name of the owner class!

We know that when creating an object from a class, each object will hold its own copy of the instance methods. That means if we create 3 objects from a class, each will have a copy of the instance methods of the target class.

But when it comes to class methods, there will only be one copy of the method!

Using class methods allows us to access class attributes (but we can’t use instance methods to access a class attribute!).

Also, in order to call a class method, we use the name of the owner class! But we can’t use objects to access class methods!

The overall structure of a class method is not different from a typical method, with one exception:

– While we use the `self` keyword to bind a method to the object that invokes it, we use `cls` to bind a class method to the class that invokes it.

Also, in order to create a class method, we need to put the annotation `@classmethod` before the target method. (Check the syntax below)

Python Class Method Declaration

class ClassName: 
    @classmethod
    def functionName(cls):
        #body…

In order to create a class method, we first need to put the `@classmethod` annotation on top of the target method. After that, the first parameter of the method should be `cls`. This parameter binds the method to the class that invokes it. Basically, the `cls` is the representation of the class that will invoke the method and, using this parameter, we can access other class members of the target class (class members means other class methods or class attributes).

Example: creating python class method

class Parent: 
    classAttribute = "This is a class attribute"
    def __init__ (self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        
    def instanceMethod(self):
        print(f"This is an instance method!")

    @classmethod
    def classMethod2(cls):
        print("Hello from class method 🙂 ")
        print(f"The value of the classAttribute is: {cls.classAttribute}")

    @classmethod
    def classMethod(cls,param1, param2):
        return param1 * param2

In this example, the `Parent` class has two class methods, `classMethod` and `classMethod2`.

The `classMehtod` takes three parameters:

– cls: this is automatically will be assigned by the python itself when the method is being invoked and basically will bind to the target class.

– param1 and param2: these parameters are just typical parameters.

The other class method is called `classMethod2` and it has only one parameter `cls` which will be automatically assigned (it will bind to the class that will invoke the method).

How to Access Python Class Methods?

In order to access a class method, we use the name of the owner method + dot `.` operator and finally the name of the class method that comes after the dot operator.

Example: Accessing Python Class Methods

class Parent: 
    classAttribute = "This is a class attribute"
    def __init__ (self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        
    def instanceMethod(self):
        print(f"This is an instance method!")

    @classmethod
    def classMethod2(cls):
        print("Hello from class method 🙂 ")
        print(f"The value of the classAttribute is: {cls.classAttribute}")

    @classmethod
    def classMethod(cls,param1, param2):
        return param1 * param2


print(Parent.classMethod(40, 60))

Parent.classMethod2()

Output:

2400

Hello from class method 🙂

The value of the classAttribute is: This is a class attribute

Here we’ve called the `classMethod` and `classMethod2` using the `Parent` class, so this means these two methods are now bounded to the `Parent` class. So the `cls` parameter represents the `Parent` class and we can use the cls to access and modify (if needed) other class methods or class attributes of the `Parent` class.

Leave a Reply