记录学习python装饰器

来源:互联网 发布:解压软件 mac 编辑:程序博客网 时间:2024/05/16 07:03

python的难点:

一、装饰器

二、迭代器

三、闭包

四、生成器

个人学习来看,难就难在两点:一是如何实现,二是有何用处;

首先先推一个学习装饰器的教科书般的地址:http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

先学习下装饰器,下面是例子。

1.#!/usr/loal/env python

def fun1(this):
    print "one"
    this()
    print "three"
    return this


@fun1
def fun2():
    print "two"

fun2()

# 注意三点:1.fun1必须有参数 2.fun1必须有返回值 3.fun2上面有个@

# 这个形式的 会多执行一次fun2,因为return会再调用一次

def fun3(this):
    print "one"
    this()
    print "three"
    return this
def fun4():
    print "two"

fun4=fun3(fun4)

#这个就是不用装饰器,同种功能实现的形式

def fun5(this):
    def _fun6():
      print "one"
      this()
      print "three"
    return _fun6
@fun5
def fun7():
    print "two"


fun7() 

#通过装饰器里面,嵌套一个子函数,实现了不会重复两次。


总结:装饰器是函数调用,调用的参数是另一个函数;为的是提高代码复用。



迭代器,如下图。


    元组、列表、字典,通过iter函数后,就可以生成一个迭代器。

    迭代器的使用。


用next逐个输出,输出完之后,用一个StopIteration来告诉我们输出完毕。迭代器常用于大数据。


0 0