Python闭包和装饰器

闭包可以简单的理解为: 函数嵌套函数,外层函数返回内层函数.
来看一个简单的例子.
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值