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

阿喀琉斯

我正在尝试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都是字符串,但是您可能想要几个小时并以浮点数付款;有关输入验证的更多信息,请参见此处

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章