I am trying to make a list of instances of one class, each with different attribute values, using this code:
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
I had the intention of making each instance named after a number (hence lectroidNames = range(0,6)
) but when I print lectroidNames
I don't get a list of numbers or a list of instances. This is the output from 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>]
I want to make a list of the scores from each instance. I tried to do this using print lectroidNames.score
but I got this error message:
AttributeError: 'list' object has no attribute 'score'
Why do I receive this error message when I made each instance have the attribute score? How can I gain the list of scores for each instance?
You could do something like,
$ 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)
Output:
$ 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')