__iter__在Class文件中,用于循环

时间:2018-09-26 00:56:59

标签: python

我目前正在上课

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

1 个答案:

答案 0 :(得分:3)

您的People类显然只存储一个人的信息,因此,如果您打算将其收集为多个人,则应将PersonPeople划分为两个单独的类, 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