function not giving back total - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: function not giving back total (/thread-29263.html) |
function not giving back total - SephMon - Aug-25-2020 Hello there New to python, I have a background in java, I'm finding oop in python confusing, this program simply prints out employee info and its suppose calculate their wage, when I run the program it just displays 0, any help appreciated thanks. class Pay(): def __init__(self, name, age, hoursWorked, amount_per_hour, total): self.name(name) self.age(age) self.hoursWorked(hoursWorked) self.amount_per_hour = amount_per_hour self.total = total def name(self): return self.__name def name(self, newname): if not newname: raise Exception("NAME FIELD CANNOT BE EMPTY") self.__name = newname def age(self): return self.__age def age(self, newvalue): if newvalue < 18: raise Exception("INVALID AGE") self.__age = newvalue def hoursWorked(self): return self.__hoursWorked def hoursWorked(self, newhours): if newhours < 0: raise Exception("HOURS MUST BE ENTERED") self.__hoursWorked = newhours def amount_per_hour(self): return self.__amount_per_hour def amount_per_hour(self, newamount): self.__amount_per_hour = newamount def total(self): return self.__total def total(self, newtotal): self.__total = newtotal def calculate_wage(self): self.total = self.hoursWorked * self.amount_per_hour return self.total def __str__(self): return "Name: " + self.__name + "\nAge: " + str(self.__age) + "\nHourWorked: " + str( self.__hoursWorked) + "\nAmount per Hour: " + str(self.amount_per_hour) + "\nTotal: " + str(self.total) p = Pay("Kevin", 34, 40, 9.80, 0) print(p)The output Quote:Name: Kevin Total field is 0 but I want it to display total wage. RE: function not giving back total - deanhystad - Aug-25-2020 Python does not support polymorphism based on the signature. Each time you you use the same name for a method it replaces the previous method declaration. def total(self): # This method is thrown away because of the method below. return self.__total def total(self, newtotal): # This method replaces the total method defined above self.__total = newtotalI think you want to use properties. https://docs.python.org/3.8/library/functions.html#property The total field is 0 because you initialize total to zero and never change it. I would not make total a variable in class because it can be calculated from hours and hourly wage. If you want to have a total in Pay you'll have to compute total each time hours or pay rate is changed. |