Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 26, 2021 07:19 pm GMT

Classmethod vs Staticmethod in Python's OOP

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

@classmethoddef 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;

By class e.g class.method()

By object e.g object.method()


Original Link: https://dev.to/charlesxstorm/classmethod-vs-staticmethod-in-python-s-oop-4ck0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To