Python装饰器

作者: 某尤 | 来源:发表于2017-02-13 15:59 被阅读24次

1. 函数

def foo():
    return 1

foo()

2. 作用域

全局作用域与本地作用域

a = "a global variable"

def foo():
    print locals()

print globals()
# {'a': 'a global variable', ...}

foo() # 2
# {}

内置函数 globals 返回一个包含所有 Python 解释器知道的变量名称的字典。

在#2调用了函数并把内部本地作用域里面的内容打印出来。函数foo有自己独立的命名空间。

3. 变量解析规则

在 Python 的作用域规则里,创建变量一定会在当前作用域里创建一个变量,但是访问或者修改变量时会先在当前作用域查找变量,如果没有找到匹配的变量会依次向上在闭合的作用域里进行查找。

a = "a global variable"

def foo():
    print a # 1

foo()
# a global variable

在#1处,Python 解释器会尝试查找变量 a,在函数本地作用域是找不到的,所以接着会去上层作用域里查找。

如果在函数foo里对全局变量赋值,结果却与想的不一样:

a = "a global variable"

def foo():
    a = "test" # 1
    print locals()

foo()
# {'a': 'test'}
a
# 'a global variable'

全局变量可以在函数内部被访问到,但赋值不行。在#1处,实际创建了一个局部变量,同名的全局变量无法被访问到。

4. 变量生存周期

变量不仅生存在一个个命名空间内,他们都有自己的生存周期。

def foo():
    x = 1

foo()
print x #1
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
# NameError: name 'x' is not defined

1处发生的错误不仅仅是因为作用域规则导致的。它还和Python以及其他很多编程语言中函数调用实现的机制有关。在这个地方这个执行时间点变量x不存在。函数foo的命名空间随着函数调用开始而开始,结束而销毁。

5. 函数参数

参数会变成本地变量存在于函数内部。

def foo(x):
    print locals()

foo(1)
# {'x': 1}
def foo(x, y=0): # 1
    return x - y

foo(3, 1) # 2

2
foo(3) # 3
3

foo() # 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes at least 1 argument (0 given)

foo(y=1, x=3) # 5
2

6. 嵌套函数

Pyhton 允许创建嵌套函数。作用域和变量生存周期依旧适用。

def outer():
    x = 1
    print locals()
    def inner():
        print x # 1
        print locals()
    inner() # 2

outer()
1

7. 函数是 Python 里的一级类对象

Python 里的函数与其他类型一样都是对象。

issubclass(int, object) # Python 中所有对象均继承自 object
True

def foo():
    pass

foo.__class__
<type 'function'>

issubclass(foo.__class__, object)
True

将函数作为参数传递:

def add(x, y):
    return x + y

def sub(x, y):
    return x - y

def apply(func, x, y): # 1
    return func(x, y)  # 2

apply(add, 2, 1) # 3
3

apply(sub, 2, 1)
1

将函数作为返回值传递:

def outer():
    def inner():
        print "Inside inner"
    return inner

foo = outer()
foo
<function inner at 0x>
foo()
Inside inner

8. 闭包

def outer():
    x = 1
    def inner():
        print x # 1
    return inner

foo = outer()
foo.func_closure
(<cell at 0x1007397f8: int object at 0x...)

Python支持一个叫做函数闭包的特性,用人话来讲就是,嵌套定义在非全局作用域里面的函数能够记住它在被定义的时候它所处的封闭命名空间。这能够通过查看函数的func_closure属性得出结论,这个属性里面包含封闭作用域里面的值(只会包含被捕捉到的值,比如x,如果在outer里面还定义了其他的值,封闭作用域里面是不会有的)

9. 装饰器

装饰器其实就是一个闭包。

def outer(some_func):
    def inner():
        print "before some_func"
        ret = some_func() # 1
        return ret + 1
    return inner
def foo():
    return 1
decorated = outer(foo) # 2
decorated()
before some_func
2

接下来写一个有用的装饰器:

class Coordinate(object):
     def __init__(self, x, y):
         self.x = x
         self.y = y
     def __repr__(self):
         return "Coord: " + str(self.__dict__)
def add(a, b):
     return Coordinate(a.x + b.x, a.y + b.y)
def sub(a, b):
     return Coordinate(a.x - b.x, a.y - b.y)
one = Coordinate(100, 200)
two = Coordinate(300, 200)
add(one, two)
Coord: {'y': 400, 'x': 400}

如果加减函数需要一些边界检查的行为怎么办?

现在期望是这样:

one = Coordinate(100, 200)
two = Coordinate(300, 200)
three = Coordinate(-100, -100)
sub(one, two)
Coord: {'y': 0, 'x': -200}
add(one, three)
Coord: {'y': 100, 'x': 0}

边界检查的装饰器:

def wrapper(func):
     def checker(a, b): # 1
         if a.x < 0 or a.y < 0:
             a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0)
         if b.x < 0 or b.y < 0:
             b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0)
         ret = func(a, b)
         if ret.x < 0 or ret.y < 0:
             ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 else 0)
         return ret
     return checker
add = wrapper(add)
sub = wrapper(sub)
sub(one, two)
Coord: {'y': 0, 'x': 0}
add(one, three)
Coord: {'y': 200, 'x': 100}

10. 使用 @ 标识符将装饰器应用到函数

Python 2.4 支持使用标识符 @ 将装饰器应用在函数上。

以前的写法:

add = wrapper(add)

使用@:

@wrapper
def add(a, b):
    return Coordinate(a.x + b.x, a.y + b.y)

使用 @ 与先前简单的用包装方法替代原有方法是一模一样的。只是用了一个语法糖让装饰的行为更优雅。

11. *args**kwargs

arg 和 kwargs 并不是 Python 语法的一部分,但在定义函数的时候,使用这样的变量名算是一个不成文的约定。

def one(*args):
    print args # 1

one()
()

one(1, 2, 3)
(1, 2, 3)

def two(x, y, *args): # 2
    print x, y, args

two('a', 'b', 'c')
a b ('c',)
def foo(**kwargs):
     print kwargs
foo()
{}
foo(x=1, y=2)
{'y': 2, 'x': 1}
dct = {'x': 1, 'y': 2}
def bar(x, y):
     return x + y
bar(**dct)
3

12. 更通用的装饰器

def logger(func):
     def inner(*args, **kwargs): #1
         print "Arguments were: %s, %s" % (args, kwargs)
         return func(*args, **kwargs) #2
     return inner

@logger
def foo1(x, y=1):
    return x * y

@logger
def foo2():
    return 2

foo1(5, 4)
Arguments were: (5, 4), {}
20

foo1(1)
Arguments were: (1,), {}
1

foo2()
Arguments were: (), {}
2

相关文章

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • Python 装饰器填坑指南 | 最常见的报错信息、原因和解决方

    Python 装饰器简介装饰器(Decorator)是 Python 非常实用的一个语法糖功能。装饰器本质是一种返...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • python3基础---详解装饰器

    1、装饰器原理 2、装饰器语法 3、装饰器执行的时间 装饰器在Python解释器执行的时候,就会进行自动装饰,并不...

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

网友评论

    本文标题:Python装饰器

    本文链接:https://www.haomeiwen.com/subject/fjctwttx.html