如何在Python 3.7的类中使用另一个实例变量从一个方法添加参数? [英] How to add parameter from one method with another instance variable in class of Python 3.7?

查看:260
本文介绍了如何在Python 3.7的类中使用另一个实例变量从一个方法添加参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试编写一个代码,其中我的程序将打印员工的信息,然后会有另一种方法,我可以传递一个参数(整数),并且不会返回任何东西,但是当我将调用该方法时它将会使用实例变量之一添加该整数(在我的情况下使用self.pay)。我的问题是我很困惑如何调用该方法,所以我需要一些帮助。



我的代码是:



I want to try write a code where my program will print information of the employee and then there will be another method where I can pass a parameter (integer) and that will not return anything but when I will call the method it will add that integer with one of the instance variable (in my case with self.pay). My problem is I am confused how can I call that method and so I need some help.

My code is:

class Information:
    def__init__ (self,first,last,pay):
        self.first = first
        self.last = last
        self.pay = pay

    def __str__(self):
        return self.first + self.last + "will get" + str(self.pay)
emp1 = Information("tom","jerry",555666)
    def extra(self):
        self.bonus = int(self.bonus + self.pay)
calling_method = self.bonus
print (calling_method)







如果有人可以帮助我,我真的很感激。谢谢。



我尝试了什么:



我试过在额外方法之后写emp1但在这种情况下我得到了一个名称错误。




I would really appreciate if someone can help me out. Thank you.

What I have tried:

I have tried to write "emp1" after "extra" method but in that case I got a name error.

推荐答案

试试这个:

Try this:
class Information:
    def __init__ (self,first,last,pay):
        self.first = first
        self.last = last
        self.pay = pay

    def __str__(self):
        return self.first + " " + self.last + " will get " + str(self.pay)

    def extra(self, value):
        print("adding bonus of ", value)
        self.pay += value

emp1 = Information("tom","jerry",555666)
print(emp1)
emp1.extra(111)
print(emp1)


这篇关于如何在Python 3.7的类中使用另一个实例变量从一个方法添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆