Trying to create an object via a user's input

后端 未结 3 1298
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 15:36

I\'m trying to create an employee object via user input, but I\'m running into issues with my code. When I run this nothing happens and it\'s not throwing any e

3条回答
  •  自闭症患者
    2021-01-07 16:13

    Your current code has a neverending loop in it, as __init__ and create_employee call each other. You take arguments for all the attributes in the initialiser, then ignore them and ask for user input, which you pass to the initialiser for a new object, which ignores it and...

    I think what you want is a structure more like:

    class Employee(object): # PEP-8 name
    
        def __init__(self, name, pay, hours):
            # assign instance attributes (don't call from_input!)
    
        def __str__(self):
            # replaces emp_name, returns a string 
    
        @property
        def weekly_total(self):
            return sum(self.hours)
    
        @classmethod
        def from_input(cls):
            # take (and validate and convert!) input
            return cls(name, pay, hours)
    

    Which you can use like:

    employee = Employee("John Smith", 12.34, (8, 8, 8, 8, 8, 0, 0))
    print str(employee) # call __str__
    

    Or:

    employee = Employee.from_input()
    print employee.weekly_total # access property
    

    Note that rather than having separate instance attributes for the different days, I've assumed a single list/tuple of hours for each day. If the day names are important, use a dictionary {'Monday': 7, ...}. Remember that all raw_input is a string, but you probably want hours and pay as floats; for more on input validation, see here.

提交回复
热议问题