Sunday 12 September 2021

Class methods in Python

Class methods are bound the class rather than object.

 

Using classmethod function

‘classmethod’ is a python built-in function, used to transform a method into a class method.

 

Syntax

classmethod(function)

 

‘classmethod’ function takes the function name as a parameter and return the converted class method.

 

Example

Employee.countEmps = classmethod(Employee.noOfEmployees)

 

Find the below working application.

 

classMethodDemo1.py

class Employee:
    """ Employee class """
    totalEmployees=0  # Class level variable
  
    def __init__(self, id, firstName, lastName):
        self.id = id
        self.firstName = firstName
        self.lastName = lastName
        Employee.totalEmployees = Employee.totalEmployees + 1
  
    def noOfEmployees(cls):
        return Employee.totalEmployees

Employee.countEmps = classmethod(Employee.noOfEmployees)

emp1 = Employee(1, "Krishna", "Gurram")
print("Total Employees", Employee.countEmps())

emp2 = Employee(1, "Lahari", "Thulasi")
print("Total Employees", Employee.countEmps())

 

Output

Total Employees 1
Total Employees 2

 

Using @classmethod decorator

you can define a class method using @classmethod decorator.

 

Example

@classmethod
def noOfEmployees(cls):
	return Employee.totalEmployees

 

Find the below working application.

 

classMethodDemo2.py

 

class Employee:
    """ Employee class """
    totalEmployees=0  # Class level variable
  
    def __init__(self, id, firstName, lastName):
        self.id = id
        self.firstName = firstName
        self.lastName = lastName
        Employee.totalEmployees = Employee.totalEmployees + 1
  
    @classmethod
    def noOfEmployees(cls):
        return Employee.totalEmployees

emp1 = Employee(1, "Krishna", "Gurram")
print("Total Employees", Employee.noOfEmployees())

emp2 = Employee(1, "Lahari", "Thulasi")
print("Total Employees", Employee.noOfEmployees())

 

Output

Total Employees 1
Total Employees 2

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment