Course
Class Methods
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
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 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.33
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.
@classmethoddef 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.
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.