Help Center

Python Class Methods: Functions Associated with Classes

Python class methods, Methods in Python classes, Defining class methods in Python 1
Print

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 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 is the prescribed way to define a class method as it is more convenient than first declaring an instance method and then transforming to a class method.

@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 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.

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.


Was this answer helpful?

Still need a hand?

Our support team is on standby if this article didn't fully answer your question.

« Back