首页 > 解决方案 > 从文件内容创建类对象

问题描述

我需要从每个员工有 3 个描述符的文件中读取,这些描述符由制表符分隔(名字、姓氏和工资)。然后根据我在文件中读取的内容创建员工对象,但我在这里偏离了标记,有人可以帮忙吗?我尝试过使用和不使用上下文管理器、不同的文件类型(csv 和 txt),但我仍然无法从中创建对象。PS:在同一个文件中,我有一个具有相同参数的预制员工类,将包含在代码中。


class Employee:

    def __init__(self, first, last, pay, bonus=0):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + "." + last + "@company.com"
        self.bonus = bonus

    def get_pay(self):
        return self.pay

    def set_pay(self, pay1):
        self.pay = pay1

    def get_full_name(self):
        return '{} {}'.format(self.first, self.last)

    def get_bonus(self):
        return self.bonus

    def set_bonus(self, bonus):
        self.bonus = bonus


def main():
    employees = []
    f = open('dirany.csv').readlines()
    for line in f:
        employee = line.split('\t')
        fname = employee[0]
        lname = employee[1]
        salary = employee[2]

    print(line)

标签: pythondata-structures

解决方案


你很近;您只需要调用Employee并将结果放入您的列表中。

def main():
    employees = []
    with open('dirany.csv') as f:
        for line in f:
            employee = line.split('\t')
            fname = employee[0]
            lname = employee[1]
            salary = employee[2]
            employees.append(Employee(fname, lname, salary))

顺便说一句,如果您定义的 get 和 set 方法除了 get 和 set 属性值之外什么都不做,则不需要它们。直接使用属性即可。

class Employee:

    def __init__(self, first, last, pay, bonus=0):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + "." + last + "@company.com"
        self.bonus = bonus

    def get_full_name(self):
        return '{} {}'.format(self.first, self.last)

    # You might make full_name a property instead of
    # an ordinary method.
    # @property
    # def full_name(self):
    #     return '{} {}'.format(self.first, self.last)

推荐阅读