如何通过实例方法传递整数并将其与实例变量一起添加?

问题描述 投票:0回答:2

我试图用实例变量bonus添加参数self.pay(将采用整数),并希望用工人的名字打印最终付款。但是,我无法打印增加的总付款

我想调用方法rise()而不是从它返回任何东西,但我很困惑如何调用它并传递一个整数。

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)
python python-3.x class parameter-passing instance-variables
2个回答
1
投票
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)

0
投票

我试过下面的代码。

我更新了def涨(自我,int(奖金)):def def(自我,奖金):

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

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


    def rise(self,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)
    emp1.rise(89)
    print (emp1)
© www.soinside.com 2019 - 2024. All rights reserved.