您的位置:首页 > 编程语言 > Python开发

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: