Python列表来存储类实例? [英] Python list to store class instance?

查看:108
本文介绍了Python列表来存储类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个python类class Student():和一个列表names = [];然后我想创建Student()的几个实例,并将它们添加到列表names

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)

我的问题是:如何创建一个列表(可以通过任何语句完成)以存储Student的实例?或者更确切地说,当我编写names = []时,如何声明names中的每个元素都是Student的实例,以便即使python是弱类型,我也可以使用该元素的属性?我希望我能说清楚;)

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 ;)

我可以这样写吗:

    for i in range(len(names)):
        student = Student()
        student = names[i]
        if student.gender == "Male":
            # Whatever

我想不是...

推荐答案

您是否尝试过上面的代码?它应该工作正常.您可以将其压缩为:

Did you try your code above? It should work fine. You can condense it into:

scores = [ student.name for student in names if student.gender == "Male" ]

请注意,调用列表names会产生误导,因为它是Student实例的列表.

Note that calling the list names is misleading, since it is a list of Student instances.

您不能将列表定义为Student实例的列表.那不是Python的工作方式.

You can't define the list to be a list of Student instances; that's not how Python works.

您要询问如何创建称为names的列表吗?

Are you asking how to create the list that you've called names?

names = [ ]
for ( score, gender ) in <some-data-source>:
    names.append( Student( score, gender ) )

当然等同于

names = [ Student( score, gender ) for score, gender in <some-data-source> ]

,然后转至

names = [ Student( *row ) for row in <some-data-source> ]

如果您需要对每一行进行大量处理,则可以将处理移到单独的函数中,也可以使用for循环.

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 for loop.

def process_row( row ):
    ...
    return score, gender

names = [ Student( *process_row( row ) ) for row in <some-data-source> ]


响应您的编辑,我认为您正在尝试声明Python中的变量类型.您写道:


Responding to your edit, I think you are trying to declare the types of variables in Python. You wrote:

for i in range(len(names)):
    student = Student()
    student = names[i]
    if student.gender == "Male":
        # Whatever

student = Student()行的目的是什么?您是否要声明变量student的类型?不要那样做以下将完成您的预期目标:

What is the purpose of the line student = Student() -- are you trying to declare the type of the variable student? Don't do that. The following will do what you intended:

for student in students:
   if student.gender == "Male":
       # Whatever

注意几件事:

  1. 我们不需要遍历range(n)然后在names中查找每个实例;遍历容器的每个元素是for循环的目的.
  2. 您不需要声明student是什么-它可以是字符串,布尔值,列表,Student等.这是动态打字.同样,students不必是列表.您可以遍历任何 iterable .
  3. 编写student.gender时,Python将获得studentgender属性,如果没有,则会引发异常.
  1. We don't need to iterate over range(n) and then look up each instance in names; iterating over every element of a container is the purpose of a for loop.
  2. You don't need to make any claims about what student is -- it could be a string, a boolean, a list, a Student, whatever. This is dynamic typing. Likewise, students doesn't have to be a list; you can iterate over any iterable.
  3. When you write student.gender, Python will get the gender attribute of student, or raise an exception if it doesn't have one.

这篇关于Python列表来存储类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆