这个问题已经在这里有一个答案:
- 如何创建一个可变数量的变量? 13个回答
我从.txt文件中读取文本,需要使用我解读为一个类的实例变量的数据之一。
class Sports:
def __init__(self,players=0,location='',name=''):
self.players = players
self.location = location
self.name = name
def __str__(self):
return str(self.name) + "is played with " + str(self.players) + " players per team on a/an " + self.location + "."
def makeList(filename):
"""
filename -- string
"""
sportsList = []
myInputFile = open(filename,'r')
for line in myInputFile:
record = myInputFile.readline()
datalist = record.split()
sportsList.append(datalist[0])
datalist[0] = Sports(int(datalist[1]),datalist[2],datalist[3])
myInputFile.close()
print(football.players)
makeList('num7.txt')
我需要转换数据列表[0],它是一个字符串,一个变量名称(基本上没有引号),因此它可以被用来创建该名称的一个实例。