Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Operator Overloading issue
#1
Why does my code give an error when i try to do dev_1 + dev_2 + dev_3?
I have explicitly defined the __add__ method within my Employee class and since Developer class inherits this class, I imagine I don't need to re-declare a separate __add__ method within the Developer class unless I wanted it to do something totally different.


class Employee:

    numberOfStaff = 0
    raise_amount = 1.04

    def __init__(self, firstname, lastname, pay):
        self.firstname = firstname
        self.lastname = lastname
        self.pay = int(pay)
        Employee.numberOfStaff += 1

    def fullName(self):
        return f"{self.firstname} {self.lastname}"

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amount)

    @classmethod
    def set_raise_amount(cls, amt):
        cls.raise_amount = amt

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

    @staticmethod
    def is_workday(myDay):
        import datetime
        r_myDay = datetime.datetime.strptime(myDay,"%d/%m/%Y")
        r_myDay.strftime("%d/%m/%Y")
        if r_myDay.weekday() == 5 or r_myDay.weekday() == 6:
            return False
        else:
            return True

    def __repr__(self):
        return f"{type(self).__name__}({self.firstname}, {self.lastname}, {self.pay})"

    def __str__(self):
        return f"{self.fullName()}"

    def __add__(self, other):
        return self.pay + other.pay


class Developer(Employee):

    raise_amount = 1.6

    def __init__(self, firstname, lastname, pay, prog_lng):
        super().__init__(firstname, lastname, pay)
        self.prog_lng = prog_lng

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


class Manager(Employee):

    def __init__(self, firstname, lastname, pay, employees=None):
        super().__init__(firstname, lastname, pay)
        if employees is None:
            self.employees = []
        else:
            self.employees = employees

    def add_employee(self, emp):
        if emp not in self.employees:
            self.employees.append(emp)

    def remove_employee(self, emp):
        if emp in self.employees:
            self.employees.remove(emp)

    def print_employees(self):
        if len(self.employees) > 0:
            for emp in self.employees:
                print("-->", emp.fullName())



dev_1 = Developer("Billy", "Smith", 70000, "Python")
dev_2 = Developer("Ted", "Jones", 65000, "Java")
dev_3 = Developer("Rose", "Allen", 80000, "Scala")

mng_1 = Manager("Samantha", "Butcher", 120000, [dev_1, dev_2])
mng_1.print_employees()
print(Manager.__dict__)

print(isinstance(mng_1,Manager))
print(issubclass(Employee, Manager))

print(dev_1)
print(mng_1)

print(dev_1 + dev_2 + dev_3)
Reply
#2
your implementation of __add__ is such that you can sum only instances of class that has pay attribute.
when you do print(dev_1 + dev_2 + dev_3). It first evaluates dev_1+dev_2. Your Employeee.__add__() method returns int. Then it try to add int and instance of class Developer and you get the error:
Error:
TypeError: unsupported operand type(s) for +: 'int' and 'Developer'
As you can see left-hand side is int - that's the result of dev_1 + dev_2.

If it was problem with missing method (as you suggest) you will get different error:
Error:
TypeError: unsupported operand type(s) for +: 'Developer' and 'Developer'
in order to work as you expect (and also you can use sum() function on e.g. list of instances), implement __radd__() method

    def __radd__(self, other):
        return other + self.pay
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
You can make the operator overloading work (using radd), but does it make any sense to sum employees?
Reply
#4
thanks buran, that did the trick though I have never stumbled across this concept radd.
Reply
#5
Check Emulating numeric types
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  operator overloading won't work MaartenRo 1 1,818 Aug-04-2020, 02:37 AM
Last Post: deanhystad
  unexpected sub result after overloading operator jolinchewjb 1 2,286 Jan-24-2019, 08:23 AM
Last Post: buran
  Program not running (Overloading problem) anurag123 2 2,574 Feb-19-2018, 07:23 PM
Last Post: nilamo
  Overloading error PyMan 1 2,324 Feb-19-2018, 04:57 AM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020