Python - Class Methods



Methods belongs to an object of a class and used to perform specific operations. We can divide Python methods in three different categories, which are class method, instance method and static method.

A Python class method is a method that is bound to the class and not to the instance of the class. It can be called on the class itself, rather than on an instance of the class.

Most of us often get class methods confused with static methods. Always remember, while both are called on the class, static methods do not have access to the "cls" parameter and therefore it cannot modify the class state.

Unlike class method, the instance method can access the instance variables of the an object. It can also access the class variable as it is common to all the objects.

Creating Class Methods in Python

There are two ways to create class methods in Python −

  • Using classmethod() Function
  • Using @classmethod Decorator

Using classmethod() Function

Python has a built-in function classmethod() which transforms an instance method to a class method which can be called with the reference to the class only and not the object.

Syntax

classmethod(instance_method)

Example

In the Employee class, define a showcount() instance method with the "self" argument (reference to calling object). It prints the value of empCount. Next, transform the method to class method counter() that can be accessed through the class reference.

class Employee:
   empCount = 0
   def __init__(self, name, age):
      self.__name = name
      self.__age = age
      Employee.empCount += 1
   def showcount(self):
      print (self.empCount)
      
   counter = classmethod(showcount)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)

e1.showcount()
Employee.counter()

Output

Call showcount() with object and call count() with class, both show the value of employee count.

3
3

Using @classmethod Decorator

Use of @classmethod() decorator is the prescribed way to define a class method as it is more convenient than first declaring an instance method and then transforming it into a class method.

Syntax

@classmethod
def method_name():
   # your code

Example

The class method acts as an alternate constructor. Define a newemployee() class method with arguments required to construct a new object. It returns the constructed object, something that the __init__() method does.

class Employee:
    empCount = 0
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Employee.empCount += 1

    @classmethod
    def showcount(cls):
        print (cls.empCount)

    @classmethod
    def newemployee(cls, name, age):
        return cls(name, age)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)
e4 = Employee.newemployee("Anil", 21)

Employee.showcount()

There are four Employee objects now. If we run the above program, it will show the count of Employee object −

4

Access Class Attributes in Class Method

Class attributes are those variables that belong to a class and whose value is shared among all the instances of that class.

To access class attributes within a class method, use the cls parameter followed by dot (.) notation and name of the attribute.

Example

In this example, we are accessing a class attribute in class method.

class Cloth:
   # Class attribute
   price = 4000

   @classmethod
   def showPrice(cls):
      return cls.price

# Accessing class attribute
print(Cloth.showPrice())  

On running the above code, it will show the following output −

4000

Dynamically Add Class Method to a Class

The Python setattr() function is used to set an attribute dynamically. If you want to add a class method to a class, pass the method name as a parameter value to setattr() function.

Example

The following example shows how to add a class method dynamically to a Python class.

class Cloth:
   pass

# class method
@classmethod
def brandName(cls):
   print("Name of the brand is Raymond")

# adding dynamically
setattr(Cloth, "brand_name", brandName)
newObj = Cloth()
newObj.brand_name()

When we execute the above code, it will show the following output −

Name of the brand is Raymond

Dynamically Delete Class Methods

The Python del operator is used to delete a class method dynamically. If you try to access the deleted method, the code will raise AttributeError.

Example

In the below example, we are deleting the class method named "brandName" using del operator.

class Cloth:
   # class method
   @classmethod
   def brandName(cls):
      print("Name of the brand is Raymond")

# deleting dynamically
del Cloth.brandName
print("Method deleted")

On executing the above code, it will show the following output −

Method deleted
Advertisements