Python list to store class instance?

后端 未结 3 1089
不思量自难忘°
不思量自难忘° 2021-02-12 23:59

Given a python class class Student(): and a list names = []; then I want to create several instances of Student() and add them into the li

3条回答
  •  醉话见心
    2021-02-13 00:09

    First of all python is not weakly typed. It is however dynamically typed so you can't specify an element type for your list.

    However this does not prevent you from accessing an object's attributes. This works just fine:

    names = [Student(1,"Male"), Student(2,"Female")]
    scores = []
    for i in names:
        if i.gender ==  "Male":
            scores.append(i.score)
    

    It is however more pythonic to write this using a list comprehension:

    names = [Student(1,"Male"), Student(2,"Female")]
    scores = [i.score for i in names if i.gender == "Male"]
    

提交回复
热议问题