Class method belongs to the class and not to the object. Class methods can only access class variables and cannot access instance variables. They can call other class methods and static methods but cannot call instance methods. Outside the class, class methods can be accessed using objects and classname as shown below-
obj.methodName() OR ClassName.methodName()
There are two ways of creating class methods-
It is the most preferred way of creating class methods. It has the following syntax-
@classmethod def functionName(cls, arg1, arg2, ...): #function body
class Person: noOfPersons = 1 @classmethod def method1(cls): #Accessing class variable via cls parameter print('Number of persons: ', cls.noOfPersons) #Accessing class variable via ClassName print('Number of persons: ', Person.noOfPersons) #Accessing class method via cls parameter cls.method2() #Accessing static method via ClassName Person.method3() @classmethod def method2(cls): print('I am another class method.') @staticmethod def method3(): print('I am a static method.') p = Person() p.method1() #Calling method via object. Person.method2() #Calling method via ClassName
Output of the above program
Number of persons: 1 Number of persons: 1 I am another class method. I am a static method. I am another class method.
Note: Using the below syntax, you can call other class and static methods from class method-
cls.MethodName() OR ClassName.MethodName()
classmethod()
is used to convert instance method to class method.
class Person: noOfPersons = 1 def display(cls): print('Number of persons:', cls.noOfPersons) p = Person() Person.display = classmethod(Person.display) Person.display()
Output of the above program
Number of persons: 1
display()
method is transformed to class method.