A little code written to understand classmethod and staticmethod
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()"
Note 02: To initiate / call other methods or staticmethod, the format is as follows; "object.method()"
Note 03: Note that staticmethods can be called in 2 ways;
Top comments (1)
Please use formatting, including for your code
python
Very useful article though.