[Tutor] classmethod - need to know what exactly it can do
Manprit Singh
manpritsinghece at gmail.com
Sun Oct 3 11:41:59 EDT 2021
Dear Sir ,
Consider an example of class that contains a class method, given below:
class StudentDetails:
"""Class for details of students"""
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
@classmethod
def fromstring(cls, details):
det = details.split(",")
return cls(det[0], int(det[1]), det[2])
def __str__(self):
return f'Name = {self.name} Age = {self.age} Sex = {self.sex}'
The class is written to store Name, age and sex of students of a class . As
far
as i have gone through texts, it clearly says, classmethod is a method in
which the first argument is the class itself, I have made a classmethod
fromstring
that has a first argument as cls. cls represents the class.
Now if have to make a record of student Rama i can do like this :
Rama = StudentDetails("Rama Singh", 21, "F")
Where "Rama Singh" is name, age is 21 and sex is "F"
For getting the details of student rama i can write
print(Rama)
Which will print :
Name = Rama Singh Age = 21 Sex = F
Now if the details of a student Ajit are given in a single string:
"Ajit Singh,21,M" where name age and sex is separated with comma, here the
classmethod fromstring is utilized, first the string is splitted with comma
as a separator which separates name age and sex then these separated details
are passed as arguments in the class, that creates new record for student
Ajit as given below:
Classmethod fromstring is called for making record of student Ajit .
Ajit = StudentDetails.fromstring("Ajit Singh,21,M")
print(Ajit) # will print the details of Ajit as given below:
Name = Ajit Singh Age = 21 Sex = M
My question is, The way i have used the classmethod is its appropriate use ?
What are other uses of class method ?
Regards
Manprit Singh
More information about the Tutor
mailing list