Python - Class Methods



An instance method accesses the instance variables of the calling object because it takes the reference to the calling object. But it can also access the class variable as it is common to all the objects.

Python classmethod() Method

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.

classmethod() Syntax

classmethod(instance_method)

classmethod() 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

Python @classmethod Decorator

Using the @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 to Define Class Method using @classmethod()

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

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.

@classmethod Decorator Example

   @classmethod
   def showcount(cls):
         print (cls.empCount)
         return
   @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.

Advertisements