我目前正在上课
class People():
def __init__(self, number ,name, age, height):
self.number = number
self.name = name
self.age= age
self.height= height
我正在尝试编写一个for循环以获取每个人,并被告知我需要编写一个 iter 我该怎么写才能做到
for i in People():
print(i.Name)
它将打印班上每个人的名字
输出为:
James
Carson,
Carlson
答案 0 :(得分:3)
您的People
类显然只存储一个人的信息,因此,如果您打算将其收集为多个人,则应将Person
和People
划分为两个单独的类, People
包含Person
实例的集合,因此您可以为__iter__
类实现People
方法,该方法返回迭代器以允许在People
上进行迭代对象以检索包含在以下内容中的Person
对象:
class Person:
def __init__(self, number, name, age, height):
self.number = number
self.name = name
self.age= age
self.height= height
class People:
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
def __iter__(self):
return iter(self.persons)
这样:
people = People()
people.add_person(Person(123, 'James', 32, 175))
people.add_person(Person(345, 'Carson', 25, 180))
people.add_person(Person(567, 'Carlson', 41, 169))
for i in people:
print(i.name)
将输出:
James
Carson
Carlson