You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python员工类列表实现求助:输出显示None且列表创建异常

问题描述

需求要求

  • 创建包含name、age、id、salary成员的employee类
  • 实现setData()方法,通过用户输入设置员工数据
  • 实现getData()方法,在控制台输出员工数据
  • 创建包含5个员工对象的列表,可通过以下方式创建:
emp_object = []
for i in range(5):
    emp_object.append(ClassName())

我尝试完成该练习并编写了如下代码,但运行后getData()输出的员工详情均为None,且列表创建不符合要求,请求帮助修正代码以实现期望输出:

class employee:
    def __init__(self, n = None, a = None, i = None, s = None):
        self.name = n
        self.age = a
        self.id = i
        self.salary = s
    def setData(self):
        self.n = input("Enter name: ")
        self.a = int(input("Enter age: "))
        self.i = int(input("Enter id: "))
        self.s = int(input("Enter salary: "))
        self.getData()
    def getData(self):
        print("Name:", self.name, self.age, self.id, self.salary)

e1 = employee()
e1.setData()

e2 = employee()
e2.setData()

e3 = employee()
e3.setData()

e4 = employee()
e4.setData()

e5 = employee()
e5.setData()

emp_object = []
for i in range(5):
    emp_object.append(employee())
print(emp_object)

期望输出

Name             id      Age     Salary
AAA              20      1       2000
BBB              22      2       2500
CCC              20      3       1500
DDD              22      4       3500
EEE              22      5       4000

修正方案

问题根源

  1. 属性赋值错误:setData方法中给self.n、self.a等临时变量赋值,而非类定义的self.name、self.age等成员,导致数据未正确存储。
  2. 列表创建不符合要求:手动创建e1-e5后,又新建了空对象列表,未将输入数据的对象加入列表。
  3. 输出格式不匹配:原getData的输出样式与期望的表格对齐格式不符。

修正后代码

class Employee:
    def __init__(self, n=None, a=None, i=None, s=None):
        self.name = n
        self.age = a
        self.id = i
        self.salary = s

    def setData(self):
        # 直接给类成员属性赋值
        self.name = input("Enter name: ")
        self.age = int(input("Enter age: "))
        self.id = int(input("Enter id: "))
        self.salary = int(input("Enter salary: "))

    def getData(self):
        # 格式化输出实现对齐
        print(f"{self.name:<16} {self.id:<8} {self.age:<8} {self.salary:<8}")

# 按要求创建员工列表并输入数据
emp_objects = []
for _ in range(5):
    emp = Employee()
    emp.setData()
    emp_objects.append(emp)

# 打印表头和所有员工数据
print(f"{'Name':<16} {'id':<8} {'Age':<8} {'Salary':<8}")
for emp in emp_objects:
    emp.getData()

修正说明

  1. 属性赋值修正:setData方法直接对self.name等类成员赋值,确保输入数据正确存储到对象中。
  2. 列表创建修正:循环创建Employee对象,调用setData输入数据后直接添加到列表,符合题目要求的创建方式。
  3. 输出格式优化:使用格式化字符串的左对齐语法f"{变量:<宽度}",让输出与期望的表格样式一致。
  4. 代码规范调整:类名改为首字母大写的Employee,符合Python PEP8编码规范。

内容的提问来源于stack exchange,提问作者Valentine Lancin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:01:16