在类中使用用户输入

时间:2017-03-18 23:03:23

标签: python

我只编程了大约一个月,我的问题是这个。一旦我在定义函数和类的类中完成,我如何将用户输入与函数一起使用。任何帮助表示赞赏可以轻松一点。

class employee:


    def __init__(self,first,last,pay,hours):
        self.first = raw_input("whats your first name")
        self.last = raw_input("whats your last name") 
        self.pay = int(input("how much do you make an hour"))
        self.hours = int(input("how many hours do you have"))



        def raise_amount(self, amount):
            self.pay = int(input('how much would you like to raise the employee pay'))



    def overtime(self,overtime):
        if self.hours !=39:
            print ("there is an error you have overtime standby")
            num1 = self.pay / 2
            overtime = num1 + self.pay
            print self.first, + self.overtime(self.hours)



print employee(self.hours)

1 个答案:

答案 0 :(得分:5)

就目前而言,这个课程没有多大意义,特别是这一点:

class employee:

    def __init__(self,first,last,pay,hours):
        self.first = raw_input("whats your first name")
        self.last = raw_input("whats your last name") 
        self.pay = int(input("how much do you make an hour"))
        self.hours = int(input("how many hours do you have"))

通过赋予__init__四个参数(除self之外),这意味着当您实例化类(通过my_employee = employee(...))时,您将必须传递所有这些参数,即在您的代码中,您必须编写my_employee = employee("John", "Cleese", "£2", "5 hours")。但这毫无意义,因为__init__函数在设置类的属性时会完全忽略所有信息,而是使用用户输入。你只想这样做:

class employee:

    def __init__(self):
        self.first = raw_input("whats your first name")
        self.last = raw_input("whats your last name") 
        self.pay = int(input("how much do you make an hour"))
        self.hours = int(input("how many hours do you have"))

    ...

my_employee = employee()

然而,创建一般员工类会更好,然后在需要通过输入创建员工的情况下,您仍然可以这样做。具体做法是:

class Employee:
    def __init__(self, first, last, pay, hours):
        self.first = first
        self.last = last
        self.pay = pay
        self.hours = hours

    ...

your_employee = Employee(input("First name: "), input("Last name: "),
    int(input("Pay: ")), int(input("Hours: ")))