我正在尝试使用以下代码列出一个类的实例列表,每个实例具有不同的属性值:
lines_stripped = ['Name', 'Age', 'Score', 'John Whorfin', '52', '1.553', 'John Emdall', '35', '1.21', 'John Parker', '41', '1.987', 'John Gomez', '33', '1.305', 'John Yaya', '41', '1.411', 'John Gant', '39', '1.6821']
header = lines_stripped[0:3]
lines_stripped = lines_stripped[3:]
class Lectroid():
def __init__ (self, Name, Age, Score):
self.name = Name
self.age = Age
self.score = Score
lectroidNames = range(0,6)
#lectroidNames = lectroidNames.append('Lectroid')
i = 0
j = 1
k = 2
x = 0
while x < 6:
lectroidNames[x] = Lectroid(lines_stripped[0], lines_stripped[1], lines_stripped[2]) #How can I not have constantly overriding lectroids
i += 3
j += 3
k += 3
x += 1
我打算使每个实例都以数字命名(因此lectroidNames = range(0,6)
),但是当我print lectroidNames
时,我没有数字列表或实例列表。这是print lectroidNames
[<__main__.Lectroid instance at 0x1085ad050>, <__main__.Lectroid instance at 0x1085ad098>, <__main__.Lectroid instance at 0x1085ad0e0>, <__main__.Lectroid instance at 0x1085ad128>, <__main__.Lectroid instance at 0x1085ad170>, <__main__.Lectroid instance at 0x1085ad1b8>]
我想列出每个实例的分数列表。我尝试使用print lectroidNames.score
来执行此操作,但收到以下错误消息:
AttributeError: 'list' object has no attribute 'score'
当我使每个实例都具有属性得分时,为什么会收到此错误消息? 如何获得每个实例的分数列表?
答案 0 :(得分:1)
您可以做类似的事情,
$ cat make.py
lines_stripped = ['Name', 'Age', 'Score', 'John Whorfin', '52', '1.553', 'John Emdall', '35', '1.21', 'John Parker', '41', '1.987', 'John Gomez', '33', '1.305', 'John Yaya', '41', '1.411', 'John Gant', '39', '1.6821']
header = lines_stripped[0:3]
lines_stripped = lines_stripped[3:]
class Lectroid():
def __init__ (self, name, age, score):
self.name = name
self.age = age
self.score = score
instances = []
data = iter(lines_stripped)
for _ in range(int(len(lines_stripped) / len(header))):
name, age, score = [next(data) for _ in range(len(header)]
instances.append(Lectroid(name, age, score))
for instance in instances:
print(instance.name, instance.age, instance.score)
输出:
$ python make.py
('John Whorfin', '52', '1.553')
('John Emdall', '35', '1.21')
('John Parker', '41', '1.987')
('John Gomez', '33', '1.305')
('John Yaya', '41', '1.411')
('John Gant', '39', '1.6821')
答案 1 :(得分:-1)
您可以定义一个空列表,然后追加:
lectroidNames =[]
i = 0
j = 1
k = 2
x = 0
while x < 6:
lectroidNames.append(Lectroid(lines_stripped[i], lines_stripped[j], lines_stripped[k]))
i += 3
j += 3
k += 3
x += 1
打印输出:
print(lectroidNames[0].name)
print(lectroidNames[1].name)
结果:
John Whorfin
John Emdall