从txt调用来定义一些东西…… Python

所以我有一个名为Person的类,基本上有构造函数名称,id,年龄,位置,目的地,我想要做的是当我想创建一个新人时,我希望它从txt文件打开.

例如,这是我的Person类(在Module,People中)

class Person :
    def __init__(self,name,ID,age,location,destination):
        self.name = name
        self.ID = ID
        self.age = age
        self.location = location
        self.destination = destination

    def introduce_myself(self):
        print("Hi,my name is " + self.name + ",my ID number is " + str(self.ID) + " I am " + str(self.age) + " years old")

import People

Fred = People.Person("Fred",12323,13,"New York","Ithaca")

Fred.introduce_myself()

所以基本上,而不是我必须手动键入那个intializer“fred,12232”等.
我希望它从包含所有已写入内容的txt文件中读取.

这就是txt文件中的内容

[Name,Age,Location,Destination]
[Rohan,111111,28,Ithaca,New Caanan]
[Oat,111112,20,New York City]
[Darius,111113,12,Los Angeles,Ithaca]
[Nick,111114,26,New Caanan,Ithaca]
[Andrew,111115,46,Ithaca]
[James,111116,34,Ithaca]
[Jennifer,111117,56,New Caanan]
[Angela,111118,22,New York City,Los Angeles]
[Arista,111119,66,Los Angeles]
最佳答案
instances = {}         #use a dictionary to store the instances

#open the file using `with` statement,it'll automatically close the
#file for you
with open('abc') as f:
    next(f)                 #skip header
    for line in f:          #now iterate over the file line by line        
        data = line.strip('[]').split(',')  #strip [] first and then split at ','
        #for first line it'll return:
            #['Rohan','111111','28','Ithaca','New Caanan'],a list object

        #Now we can use the first item of this list as the key 
        #and store the instance in the instances dict 
        #Note that if the names are not always unique then it's better to use ID as the
        #key for the dict,i.e instances[data[1]] = Person(*data)
        instances[data[0]] = Person(*data)  # *data  unpacks the data list into Person

#Example: call Rohan's introduce_myself
instances['Rohan'].introduce_myself() 

输出

Hi,my name is Rohan,my ID number is 111111 I am 28 years old

相关文章

在这篇文章中,我们深入学习了XPath作为一种常见的网络爬虫技巧。XPath是一种用于定位和选择XML文档中特...
祝福大家龙年快乐!愿你们的生活像龙一样充满力量和勇气,愿你们在新的一年里,追逐梦想,勇往直前,不...
今天在爬虫实战中,除了正常爬取网页数据外,我们还添加了一个下载功能,主要任务是爬取小说并将其下载...
完美收官,本文是爬虫实战的最后一章了,所以尽管本文着重呈现爬虫实战,但其中有一大部分内容专注于数...
JSON是一种流行的数据传输格式,Python中有多种处理JSON的方式。官方的json库是最常用的,它提供了简单...
独立样本T检验适用于比较两组独立样本的均值差异,而配对T检验则适用于比较同一组样本在不同条件下的均...