Search code examples
pythonclass-method

why should i use @classmethod when i can call the constructor in the without the annotation?


I was looking into the advantages of @classmethods and figured that we can directly call the constructor from any method, in that case, why do we need a class method. Are there some advantages which i have missed.

Why this code, what are the advantages?

class Person: 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 

    @classmethod
    def fromBirthYear(cls, name, year): 
        return cls(name, date.today().year - year) 

and not this code :-

class Person: 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 

    def fromBirthYear(name, year): 
        return Person(name, date.today().year - year) 

Solution

  • Because if you derive from Person, fromBirthYear will always return a Person object and not the derived class.

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def fromBirthYear(name, year):
            return Person(name, year)
    
    
    class Fred(Person):
        pass
    print(Fred.fromBirthYear('bob', 2019))
    

    Output:

    <__main__.Person object at 0x6ffffcd7c88>
    

    You would want Fred.fromBirthYear to return a Fred object.

    In the end the language will let you do a lot of things that you shouldn't do.