python - 从文件内容创建类对象
问题描述
我需要从每个员工有 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)
解决方案
你很近;您只需要调用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)
推荐阅读
- javascript - 我如何定义不和谐。“未定义错误不和谐”
- mysql - INSERT [LOW_PRIORITY | ] 的实际应用 延迟 | HIGH_PRIORITY] [忽略]
- android - Google 登录停止了 Play 商店构建工作
- mysql - Laravel 8:处理Mysql PDO连接超时的正确方法是什么
- python - 合并两个具有特定条件的列表
- python - Numpy errr - 对象对于所需数组来说太深
- django - 如何使用 Django 为现有表创建一对一字段?
- node.js - 为什么我不能在 linux 中更新 npm?
- mysql - mysql中date_trunc的替代品是什么?
- database - TDengine taosdump 工具正确使用指定参数