存储类实例的Python列表?
给定一个python类存储类实例的Python列表?,python,list,Python,List,给定一个python类class Student():和一个列表names=[];然后我想创建几个Student()的实例,并将它们添加到列表名称中 names = [] # For storing the student instances class Student(): def __init__(self, score, gender): self.score = score self.gender = gender 现在我想看看所有男生的分数,我
class Student():
和一个列表names=[]
;然后我想创建几个Student()
的实例,并将它们添加到列表名称中
names = [] # For storing the student instances
class Student():
def __init__(self, score, gender):
self.score = score
self.gender = gender
现在我想看看所有男生的分数,我能这样做吗
scores = []
for i in names:
if i.gender == "Male":
scores.append(i.score)
我的问题是:如何创建一个可以(如果可以通过任何语句)存储学生的实例的列表?或者更确切地说,当我编写names=[]
时,我如何声明names
中的每个元素都是Student
的一个实例,这样我就可以使用这个元素的属性,尽管python是弱类型的?我希望我说清楚;)
我可以这样写吗
for i in range(len(names)):
student = Student()
student = names[i]
if student.gender == "Male":
# Whatever
我想不是…你试过上面的代码了吗?它应该很好用。您可以将其压缩为:
scores = [ student.name for student in names if student.gender == "Male" ]
请注意,调用列表名称
会产生误导,因为它是学生
实例的列表
不能将列表定义为学生实例列表;Python不是这样工作的
您是否在询问如何创建您调用的名称
names = [ ]
for ( score, gender ) in <some-data-source>:
names.append( Student( score, gender ) )
响应您的编辑,我认为您正在尝试在Python中声明变量的类型。你写道:
for i in range(len(names)):
student = Student()
student = names[i]
if student.gender == "Male":
# Whatever
行student=student()
的用途是什么?您是否试图声明变量student
的类型?不要那样做。以下内容将实现您的预期目标:
for student in students:
if student.gender == "Male":
# Whatever
注意以下几点:
我们不需要迭代范围(n)
,然后在名称中查找每个实例;迭代容器的每个元素是for
循环的目的
你不需要对什么是student
做出任何声明——它可以是字符串、布尔值、列表、学生等。这是动态类型。同样地,学生
不必是列表;您可以迭代任何iterable
编写student.gender
时,Python将获得student
的gender
属性,如果没有异常,则会引发异常李>
首先,python不是弱类型的。但是,它是动态类型的,因此不能为列表指定元素类型
但是,这并不阻止您访问对象的属性。这很好:
names = [Student(1,"Male"), Student(2,"Female")]
scores = []
for i in names:
if i.gender == "Male":
scores.append(i.score)
但是,使用列表理解来编写此内容更具python风格:
names = [Student(1,"Male"), Student(2,"Female")]
scores = [i.score for i in names if i.gender == "Male"]
我对OOP还比较陌生,但这不是很好地满足您的需求吗name\u list
是一个类变量,每次创建新的Student
对象时,它都会添加到Student.name\u list
。例如,假设您有一个方法cheat(self)
,您希望对第三个学生执行该方法,您可以运行student.name\u list[2].cheat()
。代码:
class Student():
name_list = []
def __init__(self, score, gender):
Student.name_list.append(self)
self.score = score
self.gender = gender
#this is just for output formatting
def __str__(self):
return "Score: {} || Gender: {}".format(self.score, self.gender)
#again for output formatting
def update(): print([str(student) for student in Student.name_list])
update()
Student(42, "female")
update()
Student(23, "male")
update()
Student(63, "male")
Student(763, "female")
Student("over 9000", "neutral")
update()
输出:
[]
['Score: 42 || Gender: female']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male', 'Score: 63 || Gender: male', 'Score: 763 || Gender: female', 'Score: over 9000 || Gender: neutral']
对编辑的响应:不,您不能编写它,因为您在调用Student()
时没有参数,尽管需要2个参数。如果删除该行,它将起作用。@sepp2k,是的,参数在学生构造函数中不匹配,因此这将导致错误。嗯,我想我应该考虑一下我的问题,因为现在我在表达我的问题时遇到了困难,我发布的内容不是我的重点。如果你再仔细思考一下你的代码,你可能会明白它失败的地方。行student=student()
尝试创建一个新的student
实例,并将其存储在变量student
中。这将失败,因为构造函数缺少一些必需的参数。我认为您正在试图声明学生的类型
?您不必在Python中这样做。它将在运行时为您解决这个问题。另外请注意,您可以使用直接迭代名称的元素,并使用为学生命名:…
。感谢您的回答,我明白您的观点,但我不知道如何表达我的问题,尽管浓缩后的内容看起来相当简洁,但在某些情况下,if语句可能包含大量待办事项,这个表单可以工作吗,可能不那么简单?嗯,这意味着要做很多事情:)也就是说,如果语句1,那么实际上要做很多事情,根据大多数定义,我认为Python是弱类型的——它支持重载、隐式类型转换、多态性。。。如果这不是“弱打字”,那是什么?不可否认,这个术语并没有太大的意义。我还要说它有Python动态类型。OP只知道相反的东西:静态类型。似乎强者和弱者对于非常相似的概念来说都是相当糟糕的名字。弱类型意味着类型之间没有太大的差异。所以您可以将字符串变量添加到数字中,就像它也是一个数字一样。在python中,您必须了解变量类型。但它只能在运行时或动态中找到。@Odomontois:你能给出一个定义为弱类型的语言的例子吗?@Katrielex Perl是一个常见的例子。
names = [Student(1,"Male"), Student(2,"Female")]
scores = [i.score for i in names if i.gender == "Male"]
class Student():
name_list = []
def __init__(self, score, gender):
Student.name_list.append(self)
self.score = score
self.gender = gender
#this is just for output formatting
def __str__(self):
return "Score: {} || Gender: {}".format(self.score, self.gender)
#again for output formatting
def update(): print([str(student) for student in Student.name_list])
update()
Student(42, "female")
update()
Student(23, "male")
update()
Student(63, "male")
Student(763, "female")
Student("over 9000", "neutral")
update()
[]
['Score: 42 || Gender: female']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male']
['Score: 42 || Gender: female', 'Score: 23 || Gender: male', 'Score: 63 || Gender: male', 'Score: 763 || Gender: female', 'Score: over 9000 || Gender: neutral']