+ 3
What is the use of class methods in python?
Both examples do the same thing ,so I don't really get how is classmethod useful? class Rectangle: def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height @classmethod def new_square(cls, side_length): return cls(side_length, side_length) square = Rectangle.new_square(5) print(square.calculate_area()) class Rectangle: def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height square=Rectangle(5,5) print(square.calculate_area())
3 Answers
+ 1
classmethods, as shown in your example, are very useful to create more 'constructors'.
Imagine a class storing data, and accepting data from a lot of various file format. We could, thanks to classmethods, define a lot of 'constructors', one for each file format (from_json, from_csv,...).
+ 1
Théophile
I have a code that I wrote to make myself understand how to use classmethod ,so i wanna know if I am using it the right way ? If not, can you give an example of its right usuage please!
https://code.sololearn.com/ck85vCZjSJP1/?ref=app
To me it doesn't looks like I need any classmethod here ,I could just create a new instance with only one value
0
https://code.sololearn.com/cQLm7s4e9lxn/?ref=app
I made a very quick example. It is not doing anything special, but it shows the use of classmethods to define many 'constructors'.
The default constructor, __init__, accept a string. Then, I defined some constructors in case the input data is of type 'int', or 'bytes' or 'tuple'. In each case, I perform some operations on the input data to transform it into an acceptable format for the default constructor.
This is one of the major use of @classmethod. It is also used when we want that a class instance calls a class method as if it has been called by the class itself, and not the instance (that is quite hard to understand, I know).