Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i perform constructor overloading in python?

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)
like image 275
Jis Mathew Avatar asked Jun 16 '26 04:06

Jis Mathew


1 Answers

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

like image 127
chepner Avatar answered Jun 18 '26 19:06

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!