Home > Mobile >  Why is return included in the alternative constructor?
Why is return included in the alternative constructor?

Time:11-20

class Student:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    @classmethod    
    def from_string(cls, emp_str):
        first, last = emp_str.split("-")
        return cls(first, last)

Student_1 = Student("Cool", "Person")

Student_2 = "Another-One"

Student_2 = Student.from_string(Student_2)

Why is return used in this class method? I know you need it to work. But I'm not able to wrap my mind around why you need to include it. From what I know - in this example in the classmethod, cls(first, last) is doing the same thing as __init__(self, first, last). But why the need to include a return in there? Shouldn't just cls(first, last) be enough to call the __init__, which is what you already do when constructing the instance like Student_1?

Can you explain where my confusion lies?

CodePudding user response:

Shouldn't just cls(first, last) be enough to call the __init__, which is what you already do when constructing the instance like Student_1?

Yes, calling the constructor like this will result in __init__ being called on a new instance of cls. However, without return, that new instance will be discarded and nothing will be returned from the from_string() method.

It might be more clear if you make it a global function rather than a class method. Can you see the difference between these two functions and why the first one doesn't work?

class Student:
    ...


def student_from_string(emp_str):
    first, last = emp_str.split("-")
    Student(first, last)

student_from_string("A-B")  # None


def student_from_string(emp_str):
    first, last = emp_str.split("-")
    return Student(first, last)

student_from_string("A-B")  # Student("A", "B")

Why isn't return needed in __init__? Because you're not calling student = [new student].__init__(...), you're using student = Student(...). __init__ is a special initialization method that is not expected to return anything. You rarely call it explicitly (except on super()), but it is called automatically during a normal constructor call.

See also: https://stackoverflow.com/a/674369/23649

CodePudding user response:

You notice that from_string is a classmethod (not instance method). In the line Student_2 = Student.from_string(Student_2)

When you call from_string, it is assigned to another variable. (you are assigning to the same Student_2 )

Without return, this assignment will not happen (None will return there.)

[Note that, cls function returns an object instance]

The __instance__ and from_string are not doing the same thing here. Inside instance, you are assigning the values to instance properties. But from_string, you are calling the constructor again, to assign the parameters in the instance properties.

  • Related