[Tutor] classmethod - need to know what exactly it can do

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 3 14:32:35 EDT 2021


On 03/10/2021 16:41, Manprit Singh wrote:

> 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])

In practice you'd need to add a lot of validation code otherwise your
new instance could be full of garbage. As it is it requires the string
to be very precisely defined. But lets ignore those niceties for now...

> 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.

That's correct although its looking at it from a syntactic definition.
If you look at wider OOP books you will find out what the conceptual
use of a class method is. ie. one which operates on the class rather
than on a single instance.

> 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
...
> My question is, The way i have used the classmethod is its
> appropriate use ?
> What are other uses of class method ?

Yes, one common use of classmethods in Python is to create factory
methods that replicate the use of overloaded constructors in other
languages. fromString() is a common operation for constructing
instances from data received over a network for example.
Another common one is load(id) where the instance is created
from a database table.

Other uses include keeping a record of all instances. Class methods
can then be used to find an existing instance given some id or key,
or to provide a count of instances. Or you can ensure only unique
valued instances are created (by finding existing instances with
the same values) This approach is often used when working with
scarce resources such as network connections for example where
a pool of connection objects is created and reused when possible.

Most large scale applications will have classmethods somewhere
in the design. Smaller apps often don't need them.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list