Python闭包和装饰器
2018-03-03 21:55
337 查看
闭包可以简单的理解为: 函数嵌套函数,外层函数返回内层函数.
来看一个简单的例子.
def outFunc(x): x += 1 def inFunc(y): return x + y return inFunc a = outFunc(2) print(a(1))
装饰器其本身也是一种闭包.
def outFunc(func): print('this is outFunc.') def inFunc(y): print('this is inFunc.') return func(y) + 1 return inFunc @outFunc # aboveFunc = outFunc(aboveFunc) def aboveFunc(x): print('hello') return x * x print(aboveFunc(2))
来看看结果.
this is outFunc. this is inFunc. hello 5
@outFunc该例的语法糖, 他的含义就相当于后面的注释.@outFunc只对他下面的第一个函数有效.
python中有3个内置的装饰器.
@property@staticmethod
@classmethod
SHOW TIME
class Earth: @property # 使用@property可以让方法在调用时不加括号,就像在调用对象的属性一样. def test1(self): print('test1') @staticmethod # 使用@staticmethod可以让方法不用写入self参数,调用时也不会自动传入self. def test2(): print('test2') @classmethod # 使用@classmethod可以让方法在调用时,传入的值自动为类的值. def test3(cls): print(cls) print('test3') a = Earth() a.test1 a.test2() a.test3()
结果如下.
test1 test2 <class '__main__.Earth'> test3
相关文章推荐
- python学习笔记——闭包与装饰器
- Python闭包和装饰器
- python 嵌套函数、闭包装饰器、装饰器例子
- python 的内置函数,闭包,以及装饰器
- Python闭包、装饰器
- 深入理解python装饰器和闭包
- Python Enclosing作用域、闭包、装饰器
- python闭包和装饰器
- Python函数的作用域、闭包、装饰器
- 深入理解python中的闭包和装饰器
- python--闭包,装饰器
- python闭包与装饰器
- 【Python笔记】Python的几个高级语法概念浅析:lambda表达式 && 闭包 && 装饰器
- Python之命名空间、闭包、装饰器
- Python 进阶_闭包 & 装饰器
- Python学习之闭包
- Python中的装饰器
- 初学 Python(十五)——装饰器
- python3 闭包
- python 高阶函数:Decorator(装饰器)