加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:48:39 所属栏目:Python 来源:网络整理
导读:所以我有一个名为Person的类,基本上有构造函数名称,id,年龄,位置,目的地,我想要做的是当我想创建一个新人时,我希望它从txt文件打开. 例如,这是我的Person类(在Module,People中) class Person : def __init__(self,name,ID,age,location,destination): self.n

所以我有一个名为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,222221,28,Ithaca,New Caanan]
[Oat,222222,20,New York City]
[Darius,222223,12,Los Angeles,Ithaca]
[Nick,222224,26,New Caanan,Ithaca]
[Andrew,222225,46,Ithaca]
[James,222226,34,Ithaca]
[Jennifer,222227,56,New Caanan]
[Angela,222228,22,New York City,Los Angeles]
[Arista,222229,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','222221','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 222221 I am 28 years old

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读