在类中使用用户输入

0 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)
Run Code Online (Sandbox Code Playgroud)

Den*_*loe 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"))
Run Code Online (Sandbox Code Playgroud)

通过提供__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()
Run Code Online (Sandbox Code Playgroud)

但是,最好创建一个普通员工类,然后在需要通过输入来创建员工的情况下,仍然可以这样做。特别:

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: ")))
Run Code Online (Sandbox Code Playgroud)

  • 不过,我重申一下,只是因为我认为它确实很重要:您不应在构造函数中要求用户输入。这迫使您每次要创建Employee时都要手动键入数据。如果您已经有一个包含该信息的文件怎么办?在构造函数外部请求输入,然后将数据传递进来。 (2认同)