所以我有一个名为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()
Run Code Online (Sandbox Code Playgroud)
所以基本上,而不是我必须手动键入该初始化器"fred,12232"等.我希望它从已经写入所有内容的txt文件中读取.
这就是txt文件中的内容
[Name, ID, Age, Location, Destination]
[Rohan, 111111, 28, Ithaca, New Caanan]
[Oat, 111112, 20, Ithaca, New York City]
[Darius, 111113, 12, Los Angeles, Ithaca]
[Nick, 111114, 26, New Caanan, Ithaca]
[Andrew, 111115, 46, Los Angeles, Ithaca]
[James, 111116, 34, New Caanan, Ithaca]
[Jennifer, 111117, 56, Los Angeles, New Caanan]
[Angela, 111118, 22, New York City, Los Angeles]
[Arista, 111119, 66, New Caanan, Los Angeles]
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
输出:
Hi, my name is Rohan , my ID number is 111111 I am 28 years old
Run Code Online (Sandbox Code Playgroud)