Python3 [类]- 我应该创建一个新变量来存储来自用户输入的 class 实例吗?如何创建?

Python3 [Classes]- Should I create a new variable to store an instance of a class from a user's input, and how?

本网站的第一个问题。仍处于学习编程的早期阶段,并试图围绕一些概念进行思考。我正在努力寻找我遇到的这个问题的答案:

所以,让我们来一个简单的 class:

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

现在我想根据用户的输入实例化 class,并将该实例存储在一个变量中,然后可以将其附加到列表中,给我这样的东西:

 list_employees = [emp_1, emp_2, emp_3]   

问题是这些变量(emp_1 等等)还不存在。它们必须从输入中创建。

我明白我自己该怎么做:

emp_1 = Employee(input("Enter name: "), int(input("Enter salary: ")))

但我希望这样做 "automatically",如果这意味着什么的话,这样用户就可以创建无限数量的实例。

我不需要任何特定的东西,我可以想出解决字典问题的方法,但我的大脑只是在概念上与这个 "variable creation by the program" 想法斗争......我希望我设法清楚地表达出来,如果有人能帮助我理解这一点,或者向我解释我是否以及如何思考这个错误,我将不胜感激!

干杯!

您可以在对象实例化期间执行此操作:

class Employee():
    objects = []

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

        Employee.objects.append(self)

如果您只想将新实例附加到列表中,您实际上并不需要中间变量:

# python 2 / 3 compat
try:
   input = raw_input
except NameError:
   pass


def create_emp():
    # Q&D, would need error handling
    name = input("Enter name")
    salary = int(input("Enter salary"))
    return Employee(name, salary)


def create_emps()
    employees = []
    while True:
        employees.append(create_emp())
        answer = input("add another ? (Y/n)")
        if answer.lower().strip() != "y":
            break
    return employees

if __name__ == "__main__":   
    employees = create_emps()
    print(employees)

例如,您可以执行以下操作

employees = []
for _ in range(1,4):
    name = input("Enter name: ")
    salary = int(input("Enter salary: "))
    employees.append(Employee(name, salary))

如果您想按名称访问变量,请尝试使用字典而不是列表来保存您的员工

编辑 带字典(f strings only after Python 3.6)

employees = {}
for i in range(1, 4):
    name = input("Enter name: ")
    salary = int(input("Enter salary: "))
    employees[f'emp_{i}'] = Employee(name, salary)