Search code examples
pythonpython-3.xclassparameter-passinginstance-variables

How to pass an integer through an instance method and add that with an instance variable?


I was trying to add the parameter bonus (which will take an integer) with the instance variable self.pay and wanted to print that final payment with the worker's name. But, I could not print that added total payment

I want to call the method rise() instead of returning anything from it, but I am confused how I can call that and pass an integer number.

class Information:
    def __init__(self,first,last,pay):

        self.first = first
        self.last = last
        self.pay = pay


    def rise(self,int(bonus)):
        self.pay = self.pay + bonus

    def __str__(self):
        return "%s and %s and has a balance of %s" % (self.first,self.last,self.pay)

if __name__ == "__main__":
    emp1 = Information("tom","jerry",999)
    print (emp1)

Solution

  • class Information:
        def __init__(self,first,last,pay):
            self.first = first
            self.last = last
            self.pay = pay
    
        def raise_salary(self, bonus):
            self.pay += int(bonus) # exception if bonus cannot be casted
    
        def __str__(self):
            return "%s and %s and has a balance of %s" % (self.first,self.last,self.pay)
    
    if __name__ == "__main__":
        emp1 = Information("tom", "jerry", 999)
        print(emp1)
        emp1.raise_salary('1000') # or just emp1.raise(1000)
        print(emp1)