20
Classmethod vs Staticmethod in Python's OOP
class Area: #defining an area class
def init(self,wt,ht):
self.ht= ht
self.wt= wt
def area(self): #defining a simple rect area method
return self.wt*self.ht
@classmethod
def sqr(cls,sd): #defining a square method to take advantage of the rect area method
return cls(sd,sd)
class Tri(Area): #defining a triangle class to inherit from the area class
def area(self):
super().area() #calling the rect area method from the super_class "Area"
return int(0.5*self.wt*self.ht) #using the super_class's argument to output the triangle's area
@staticmethod
def check(var): #defining a regular function
if var>=20:
print("This triangle has a large area")
else:
print("Small area detected")
rect= Area(4,5)
sqr= Area.sqr(7) #initiating the square's area
tri= Tri(30,100)
Tri.check(tri.area()) #calling the regular function (initiating the staticmethod). This takes the format: class.method()
tri.check(tri.area()) the above can also be written this way. This takes the format: object.method()
print(rect.area(),sqr.area(),tri.area())
Note 01: To initiate a classmethod or call a staticmethod; the format is as follows "class.method()"
20