zoukankan      html  css  js  c++  java
  • Day 12 装饰器,迭代器,生成器

    day12思维导图

    一 装饰器 Decorator

    A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

    作用 Usage

    Python's decorators allow you to extend and modify the behavior of a callable (functions, methods, and classes) without permanently modifying the callable itself. Any sufficiently generic functionality you can “tack on” to an existing class or function's behavior makes a great use case for decoration

    简单的装饰器 Simple Decorators

    def my_decorator(func):
      def wrapper():
          print("Something is happening before the function is called.")
          func()
          print("Something is happening after the function is called.")
      return wrapper

    def say_whee():
      print("Whee!")

    say_whee = my_decorator(say_whee)

     

    语法糖 Syntactic Sugar

    The way you decorated say_whee() above is a little clunky. First of all, you end up typing the name say_whee three times. In addition, the decoration gets a bit hidden away below the definition of the function.

    Instead, Python allows you to use decorators in a simpler way with the @ symbol, sometimes called the “pie” syntax.

    def my_decorator(func):
      def wrapper():
          print("Something is happening before the function is called.")
          func()
          print("Something is happening after the function is called.")
      return wrapper

    @my_decorator
    def say_whee():
      print("Whee!")

    有参装饰器Decorating Functions With Arguments

    (Remain to be improved)

    二 迭代器 Iterator

    An iterator is an object that contains a countable number of values.

    An iterator is an object that can be iterated upon, meaning that you can traverse/'trævɜːs/遍历 through all the values.

    Technically, in Python, an iterator is an object which implements the iterator protocol/ˈprəʊtəkɒl/ 协议, which consist of the methods _iter_() and _next_().

    Iterator vs Iterable 迭代器与可迭代对象

    Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

    All these objects have a iter() method which is used to get an iterator:

    Looping Through an Iterator

    We can also use a for loop to iterate through an iterable object:

    The for loop actually creates an iterator object and executes the next() method for each loop.

    三 生成器 Generator

    Generator functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

    the yield keyword

    yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed as generator. Hence, yield is what makes a generator. yield keyword in Python is less known off but has a greater utility which one can think of.

    Example:

    def first_n(n):
      '''Build and return a list'''

      num, nums = 0, []
      while num < n:
          nums.append(num)
          num += 1
      return nums
    sum_of_first_n = sum(first_n(1000))
    print(sum_of_first_n)

    and use the generator to imporve it:

    def firstn(n):
      num = 0
      while num < n:
          yield num
          num += 1


    sum_of_first_n = sum(firstn(1000000))

    print(sum_of_first_n)

     

  • 相关阅读:
    设计模式——代理模式
    设计模式——建造者模式
    设计模式——模板方法
    springboot+mybatis项目自动生成
    【小坑】java下载excel文件
    设计模式——工厂方法模式 和 抽象工厂模式
    设计模式——单例模式
    容易忽略的递归当中的return
    Android 4.0以后正确的获取外部sd卡存储目录
    Android 串口设置校验位、速率、停止位等参数
  • 原文地址:https://www.cnblogs.com/fengshili666/p/14212455.html
Copyright © 2011-2022 走看看