尝试通过用户输入创建对象


问题内容

我正在尝试employee通过用户输入来创建对象,但是我的代码遇到了问题。当我运行时,什么也没有发生,也没有引发任何错误。

class employee(object):

    def __init__(self,name,pay_rate,monday,tuesday,wednesday,thursday,friday,saturday,sunday):
        self.create_employee()
        self.name = name
        self.pay_rate = pay_rate
        self.monday = monday
        self.tuesday = tuesday
        self.wednesday = wednesday
        self.thursday = thursday
        self.friday = friday
        self.saturday = saturday
        self.sunday = sunday


    def weekly_total(self):
        self.total_weekly_hours = self.monday + self.tuesday + self.wednesday + self.thursday + self.friday + self.saturday + self.sunday        
        self.emp_name()
        print "\n  Your hours this week are:", self.total_weekly_hours,"\n"


    def emp_name(self):
        print "\n  Current employee is: ",self.name


    def create_employee(self):
        self.name = raw_input("Enter new employee name")
        self.pay = input("Enter pay rate")
        self.monday = raw_input("Enter monday hours")
        self.tuesday = raw_input("tuesday hours?")
        self.wednesday = raw_input("wed hours?")
        self.thursday = raw_input("Thursday hours?")
        self.friday = raw_input("Friday hours?")
        self.saturday = raw_input("saturday hours?")
        self.sunday = raw_input("sunday hours?")
        self.object_name = raw_input("Name your object")

        self.object_name = employee(self.name,self.pay,self.monday,self.tuesday,self.wednesday,self.thursday,self.friday,self.saturday,self.sunday)
        print self.name, " was created"

问题答案:

您当前的代码中有一个永无休止的循环,__init__并且create_employee彼此调用。您在初始化程序中为所有属性获取参数,然后忽略它们并要求用户输入,然后将其传递给初始化程序以获取新对象,该对象将忽略它并…

我认为您想要的是一个更像这样的结构:

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)

您可以像这样使用:

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

要么:

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

请注意,我假设每天没有一个单独的列表/元组,而不是在不同的日期具有不同的实例属性。如果日期名称很重要,请使用字典{'Monday': 7, ...}。请记住,所有内容raw_input都是字符串,但是您可能想要几个小时并以浮点数付款;有关输入验证的更多信息,请参见此处