如何在类中为用户输入使用for循环?

2024-04-18 04:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过提供预定义的输入,使用类创建了员工详细信息。我无法将结果存储到dict中。我需要将其作为csv写入。如果您能帮助我,我将不胜感激,因为我是python的新手

以下是我的代码:

在类中使用for循环正确吗?

class Employee():
    def main(self,name,idno,position,salary):

        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def input(self):
        n=int(raw_input("Enter the number of employees:"))
        for i in range(n):
            self.name=raw_input("Name:")
            self.idno=raw_input("Idno:")
            self.position=raw_input("position:")
            self.salary=raw_input("salary:")

            print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
                  "salary:", self.salary)

if __name__=='__main__':
        result=Employee()
        result.input()

Tags: nameselfforinputrawmaindef员工
2条回答

首先,我不认为你班上的人会像你想的那样工作。由于您经常重写类变量,因此输入多个雇员是没有意义的,因为类当前只能保存一个雇员的信息。我会考虑将员工保存为字典,并在Employee(s)类中将这些字典保存为列表。在

class Employees():
    all_employees = [{...}, {...}]
    dict_keys = ["name", "idno", "position",...]
    def input(self):
        counter = 0
        n = input("Number of employees: ")
        while counter < n:
            new_employee = dict()
            for key in dict_keys:
                new_employee[key] = raw_input("{}: ".format(key))
            all_employees.append(new_employee)

if __name__ == "__main__":
    e = Employees()
    e.input()

这说明了我在评论中关于在类的外部使用for循环的内容:

class Employee(object):
    def __init__(self, name, idno, position, salary):
        self.name=name
        self.idno=idno
        self.position=position
        self.salary = salary

    def print_data(self):
        print("Name:", self.name, "Idno:", self.idno, "position:", self.position,
              "salary:", self.salary)

if __name__=='__main__':

    def input_employee_data():
        print('Enter data for an employee')
        name = raw_input("Name:")
        idno = raw_input("Idno:")
        position = raw_input("position:")
        salary = raw_input("salary:")
        print('')
        return name, idno, position, salary

    employees = list()
    n = int(raw_input("Enter the number of employees:"))
    for i in range(n):
        name, idno, position, salary = input_employee_data()
        employee = Employee(name, idno, position, salary)
        employees.append(employee)

    print('List of employess')
    for employee in employees:
        employee.print_data()

相关问题 更多 >