class method in python | what is class method in python |
Class Method :-
Class Method receive cls as implicate first argument just like an instance method receive instance .
class method take a cls parameter that point to the class and not the object instance when method is called .because the class method only has access to this class argument it can’t no modify object state .that would require access to self. However class method can still modify class state that applied across all instance of class.
Through cls parameter class method can access attributes and method on same object .
@ decorator can be applied on any method of class .this decorator will allows us to call that method using the class name instead of object .
Decorator is a function that receives another function as argument .the behavior of the argument function is extended by the decorator without actually modifying it .
Class method is one that belongs to the class as a whole .it doesn’t require an instance an. a class method decorator declare with the @classmethod decorator .
In our class method example @classmethod is applied on the any method .this method has one parameter cls , which refers to the class . using this techniques we can call class method using class name .
Class Method |
Syntax –
Class ClassName:
@classmethod
def function_name(cls ,arguments): # class method
#function body
@classmethod
def function_name(cls ,arguments): # class method
#function body
Class method Program using @decorator :-
class person:
totalobject = 0
def __init__(self):
person.totalobject=person.totalobject+1
@classmethod
def showcount(cls): #Class method
print("Total objects: ",cls.totalobject)
p1=person()
p2=person()
person.showcount() #call class method using class name
totalobject = 0
def __init__(self):
person.totalobject=person.totalobject+1
@classmethod
def showcount(cls): #Class method
print("Total objects: ",cls.totalobject)
p1=person()
p2=person()
person.showcount() #call class method using class name
Note-
class method we can call using class name or using an object/instance .above same example call class method using an object as show below .
p1=person()
p2=person()
p1.showcount()
p2=person()
p1.showcount()
Output-
Total objects:2
Add two no's using class method -
class Addition:
@classmethod
def add(cls,x,y): # classmethod
return x+y
print("Addition of two number:",Addition.add(2,4) )
@classmethod
def add(cls,x,y): # classmethod
return x+y
print("Addition of two number:",Addition.add(2,4) )
Output-
Addition of two number: 6
Post a Comment