-1
class Employee:

        def __init__(self, aname, asalary, arole):
        self.name = aname
        self.salary = asalary
        self.role = arole

    def printdetails(self):
        return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"

    @classmethod
    def change_leaves(cls, newleaves):
        cls.no_of_leaves = newleaves

    @classmethod
    def from_dash(cls, string):
        # params = string.split("-")
        # print(params)
        # return cls(params[0], params[1], params[2])
        return cls(*string.split("-"))  #what is happening from this point exactly?


harry = Employee("Harry", 255, "Instructor")
rohan = Employee("Rohan", 455, "Student")
karan = Employee.from_dash("Karan-480-Student")

print(karan.printDetails())

Here as per code, object "karan= Employee.from_dash("Karan-480-Student")", But i want to understand what exactly is happening from the point we return cls(*string.split("-")) from class method "from_dash"? Like for karan object are we passing the returned tuple to the init constructor of Employee class and assigning "karan" to name, "480" to salary and "Student" to role? or something else is going on ?

arin
  • 29
  • 4
  • Break it down. What does `string.split("-")` do? What does the `*` do? What does `Employee.__init__` method expect? – DeepSpace May 08 '22 at 14:09

1 Answers1

0
return cls(*string.split("-"))

will evaluate to

return cls(*["Karan", "480", "Student"])

The cls's __init__ will be called, in our case, the cls is Employee, who's __init__ needs aname, asalary, arole.

In our expanded statement, we have a list of 3 values, which will be unpacked (thanks to the * operator) and mapped to the corresponding element in the __init__ method.

Tharun K
  • 1,160
  • 1
  • 7
  • 20
  • Okay..now im getting it a little bit. So this statement karan = Employee.from_dash("Karan-480-Student") is equivalent to karan= Employee(*["Karan", "480", "Student"])?? is my understanding right? – arin May 08 '22 at 14:24
  • yes, you are right – Tharun K May 08 '22 at 14:26