当前位置: 首页 > news >正文

中国网站建设调查分析中国营销网

中国网站建设调查分析,中国营销网,免费的小程序模板网站,盐渎网目录 目标 Python版本 官方文档 概述 自定义可迭代对象 自定义迭代器 目标 掌握迭代器的使用方法。了解迭代器和可迭代对象的区别。通过案例实现迭代器和可迭代对象。 Python版本 Python 3.9.18 官方文档 迭代器https://docs.python.org/3.9/glossary.html#term-iterat…

目录

目标

Python版本

官方文档

概述

自定义可迭代对象

自定义迭代器


目标

  1. 掌握迭代器的使用方法。
  2. 了解迭代器和可迭代对象的区别。
  3. 通过案例实现迭代器和可迭代对象。

Python版本

        Python 3.9.18


官方文档

迭代器https://docs.python.org/3.9/glossary.html#term-iterator


概述

迭代器

官方描述

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

理解

  1. 迭代器必然实现了__iter__()__next__()方法。
  2. __iter__()返回迭代器对象,往往返回自己即self,该方法意味着它本身是可迭代的,可以用于for循环。
  3. __next__()返回容器中的下一个元素。当没有更多元素时仍然调用该方法则抛出 StopIteration 异常。后面的迭代器案例中会讲解如何通过next()方法优雅地遍历所有元素。

可迭代对象

官方描述

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements Sequence semantics.

Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.

理解

  1. 只要实现了__iter__()或sequence语义的__getitem__()方法的对象就是可迭代对象。由此可见,迭代器必然是可迭代对象
  2. 可迭代对象是指一个能够一次返回一个成员的对象,所以常与for循环搭配使用。
  3. 常见的可迭代对象有:列表(list)、字典(dict)、元组(tuple)、字符串(str,每次迭代返回一个字符)、集合(set)、字典文件对象(每次迭代读取一行数据)。

自定义可迭代对象

需求

        创建班级类和学生信息类,一个班级包含多个学生,因此班级类提供添加学生的方法,并将学生信息循环打印。要求班级类是可迭代对象。

from collections.abc import Iterable, Iterator
class Student:def __init__(self, name, age, sex):self.name = nameself.age = ageself.sex=sexclass Classroom:def __init__(self, name):#班级名称self.name = nameself.students = []def add(self,student):#添加学生对象self.students.append(student)def __iter__(self):return selfif __name__ == '__main__':student=Student("张三",24,"男")student2 = Student("李四", 25, "男")student3 = Student("王五", 26, "女")classroom=Classroom("123班")classroom.add(student)classroom.add(student2)classroom.add(student3)for student in classroom.students:print(student.name,student.age,student.sex)#判断classroom是不是迭代器(Iterator):Falseprint(isinstance(classroom,Iterator))#判断classroom是不是可迭代对象(Iterable):Trueprint(isinstance(classroom,Iterable))# 判断classroom是不是迭代器(Iterator):Falseprint(isinstance(student, Iterator))# 判断classroom是不是可迭代对象(Iterable):Falseprint(isinstance(student, Iterable))

结果

        班级类是可迭代对象,但不是迭代器,学生类不是可迭代对象也不是迭代器。这与类是否实现__iter__()方法有关。


自定义迭代器

需求

        创建班级类和学生信息类,一个班级包含多个学生,因此班级类提供添加学生的方法,并将学生信息循环打印。要求班级类是可迭代器。且使用next()方法优雅地遍历所有元素。

from collections.abc import Iterable, Iterator
class Student:def __init__(self, name, age, sex):self.name = nameself.age = ageself.sex=sexclass Classroom:def __init__(self, name):#班级名称self.name = nameself.students = []#迭代器索引,从第一个索引开始。self.index=0def add(self,student):#添加学生对象self.students.append(student)def __iter__(self):return selfdef __next__(self):if self.index<len(self.students):student = self.students[self.index]self.index+=1return studentelse:#如果没有下一个元素则抛出StopIteration异常raise StopIteration
if __name__ == '__main__':student=Student("张三",24,"男")student2 = Student("李四", 25, "男")student3 = Student("王五", 26, "女")classroom=Classroom("123班")classroom.add(student)classroom.add(student2)classroom.add(student3)#这里我用next()方法来遍历学生对象。iterator=iter(classroom)while True:#next()方法第二个参数作用:如果没有下一个元素了,则返回设定的默认值,这里我设定的默认值是None。student=next(iterator,None)if student :print(f"姓名: {student.name}, 年龄: {student.age}, 性别: {student.sex}")else:print("遍历完成。")break;
http://www.dtcms.com/a/426393.html

相关文章:

  • 四川网站推广域名查询解析ip
  • 彩票网站开发演示做的网站如何改标题
  • 做推广的网站pt网站怎么下载与做
  • 网站备案有什么好处哪项不属于网站架构
  • 顺企网我做网站wordpress电脑访问
  • 中国河北网站黄石建网站
  • 如何提升网站的权重admin5站长网
  • 在线网站建设活动做微信公众号微网站吗
  • 凡科网站案例帝国网站制作广告
  • 做网站用asp div代码免费做代理的网站
  • 网站推广的名词解释建设移动门户
  • 中卫网站推广软件厦门园网站忱建设
  • 网站首页设计报价多少产品通过网站做营销
  • 企业网站营销常用的方法做网站的动态图片
  • 做网站工资高么公司网址平台有哪些
  • 高水平的大连网站建设wordpress 添加gif
  • 山西省网站备案免费玩游戏
  • 微信网站建设流程新手建设网站步骤
  • 哪里办网站不用备案免费空间网站怎么做的
  • 合肥网站建设 卫来网络怎么制作网页里面的内容
  • 网站电话素材外贸网站国际化怎么做
  • wordpress主题广告宁波seo是什么意思
  • 校园网站建设计划书嘉兴seo关键词优化
  • 网站模板 黑色为什么现在好多人嘲讽做核酸
  • 云南网站开发靳刘高设计公司官网
  • 做网站建设怎么赚钱php 企业网站开发实例
  • 阿里云主机网站开发专业做制作网站
  • 二级域名网站优化可口可乐网站建设的目的
  • 深圳网站建设服务哪个便宜点北京网址导航
  • 东莞有哪些做网站办公室装修图片大全