Python之路Day11

函数名的第一类对象及使用

  1. 当作值,赋值给变量

    • def func():
          print(1)
      print(func)  #查看函数的内存地址
      a=func
      print(a)
      a()
      

        

  2. 可以当作容器中的元素

    • def func():
          print(1)
      def foo():
          print(2)
      #lst.append(func)
      #lst.append(foo)
      #print(lst)
      ​
      lst=[func,foo]  #放到列表
      for i in lst:
          i()
          
      dic={}  #放到字典中
      

        

  3. 函数名可以当作函数的参数

    • def func(a):
          a()
          print(111)
      def foo():
          print(222)
          def f1():
              print(333)
          func(f1)
      foo()
      

        

  4. 函数名可以当作函数的返回值

    • def func():
          def foo():
              print(111)
          return foo
      func()()
      

        

f-strings 格式化

  • f"{}"

迭代器

  • 可迭代对象

    • list,tuple,str,set,dict 取值方式只能直接看

    • 只要具有_iter_()方法就是一个可迭代对象

      • s._iter_() -- 将可迭代对象转换成迭代器

  • 具有_iter_()和_next_()两个方法的才是迭代器

  • 迭代器再执行_iter_还是原来的迭代器

  • for 循环的本质

    • while true:
          try:
              print(s._next_())
          except StopIteration:
              break
      

        

  • iter()与_iter_()是一样的

    • python 2 中有iter() _iter_() next()

    • python 3 中iter()和_iter_() _next_()和next()都有

  • next()与_next_()是一样的

  • iter()与next()用法:
    l=iter(lst) #iter(迭代对象)
    next(l)     #next(迭代器)
  • 迭代器时基于上一次停留的位置,继续取值,不能取超,否则会报错

  • 迭代器优点:

    • 惰性机制 -- 节省空间

  • 迭代器缺点:

    • 不能直接查看值,迭代器查看到的时迭代器的内存地址

    • 一次性,用完就没了

    • 不能逆行

  • 空间换时间:容器存储大量的元素,取值时间短,但是容器占用空间较大

  • 时间换空间:虽然节省了空间,但是取值时间较长

  •  

原文地址:https://www.cnblogs.com/zlx960303/p/11959441.html