3

I have an employee class which I would like to fill in two different ways, and would like to know do this by constructor overloading

class Employee:

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    def __init__(self, data):
        (self.first, self.last, self.pay) = data

This is because, either I have to initialise the class like

Employee('John','Smith',3000)

Or I would like to initialise the class by passing a tuple like

data = ('John','Smith',3000)
Employee(data)
2
  • 3
    There is no constructor/method/function overloading in Python. You can use either optional keyword-parameters, or decide what to do based on the type of the parameter. For this specific case, however, you can just do Employee(*data), unpacking the tuple to the individual parameters. Commented Nov 14, 2019 at 14:04
  • 2
    If instead of Employee(data) you used Employee(*data), you could use the single, straight-forward constructor. Commented Nov 14, 2019 at 14:05

1 Answer 1

3

You don't, really. You could mess around with a definition like

def __init__(self, *args):

then do lots of processing that checks the number of arguments, the type of the first argument, etc. Or, you can simply be explicit and define a separate constructor whose name describes exactly what it does. The class method can do some validation on the tuple before passing its contents to the default constructor.

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

    @classmethod
    def from_tuple(cls, t):
        if len(t) != 3:
            raise ValueError("Wrong number of items in the tuple")

        return cls(*t)

data = ('John','Smith',3000)
Employee.from_tuple(data)

Of course, the simplicity of the class method's definition suggests that you don't need to go to this much trouble: if you know the tuple has the right number and kinds of values, just unpack data for use with the default constructor.

Employee(*data)

By "default constructor", I mean the method which Employee.__new__ resolves to. Employee.__init__ is technically an initializer, invoked when appropriate on an already constructed instance returned by __new__.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.