Given a python class class Student(): and a list names = []; then I want to create several instances of Student() and add them into the list names,
names = [] # For storing the student instances
class Student():
def __init__(self, score, gender):
self.score = score
self.gender = gender
And now I want to check out the scores of all the male students, can I do it like this?
scores = []
for i in names:
if i.gender == "Male":
scores.append(i.score)
My question is: How to create a list that can (if could be done by any statement) store the instance of Student? Or rather, when I write names = [], how could I state every element in names is an instance of Student so that I can use the attributs of this element despite python is weak type? I hope I made myself clear 😉
Can I write like:
for i in range(len(names)):
student = Student()
student = names[i]
if student.gender == "Male":
# Whatever
I guess not…
Did you try your code above? It should work fine. You can condense it into:
Note that calling the list
namesis misleading, since it is a list ofStudentinstances.You can’t define the list to be a list of Student instances; that’s not how Python works.
Are you asking how to create the list that you’ve called
names?which is of course equivalent to
and in turn to
If you need to do a lot of processing for each row then you can either move the processing into a separate function or use a
forloop.Responding to your edit, I think you are trying to declare the types of variables in Python. You wrote:
What is the purpose of the line
student = Student()— are you trying to declare the type of the variablestudent? Don’t do that. The following will do what you intended:Notice several things:
range(n)and then look up each instance innames; iterating over every element of a container is the purpose of aforloop.studentis — it could be a string, a boolean, a list, aStudent, whatever. This is dynamic typing. Likewise,studentsdoesn’t have to be a list; you can iterate over any iterable.student.gender, Python will get thegenderattribute ofstudent, or raise an exception if it doesn’t have one.