python装饰器和语法糖

本文介绍了Python中的函数基础知识,包括函数定义、调用及变量打印。深入探讨了嵌套函数的两种执行方式,并展示了如何返回函数。接着讲解了装饰器的概念,用于在不改变原函数的情况下拓展其功能,如实现计时器。最后提到了装饰器的使用语法糖@,并展示了带参数的装饰器应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.cnblogs.com/sweet-i/p/11177063.html
#1.函数变量
def fun():
    print('hello')

#函数调用
fun()   #hello
#打印函数变量
print(fun)#<function fun at 0x000001F09EB35160>

#2.嵌套函数--一个函数里面包含另一函数的定义
def func1():
    def func2():
        print('hello')
func1()#func2没有执行

#想要func2执行,两种方法
#2.1调用func2
def func1():
    def func2():
        print('hello')
    func2()#调用func2

func1()
#2.2返回func2的函数变量
def func1():
    def func2():
        print('hello')
    return func2  #返回函数变量 返回到func1处 注意不要加括号
res=func1()
print(res)#<function func1.<locals>.func2 at 0x000001E321E5EEE0>返回的是func2的函数地址
res()#res()==func2() 运行结果是hello

#3.返回函数  2.2就是返回函数

#
import  time
def func1():
    time.sleep(3)
    print('in func1')

def func2():
    time.sleep(5)
    print('in func2')
def timer0(func):
    start=time.time()
    func()
    print(time.time()-start)

timer0(func1)
#这种方式改变了func1的调用方式
#func1()-->func1
#in func1
#3.006218910217285


#           装饰器
#装饰器的功能
#在不改变原函数以及调用方式的情况下对原函数功能的拓展
#计时器
def timer(func):
    def inner():  #闭包函数
        start=time.time()
        func()
        print(time.time()-start)
    return inner
func1=timer(func1)#==innner
func1()#这种调用方式没有变
#in func1
#3.006218910217285

#装饰器升级
#为了简化装饰器的调用,用语法糖@装饰器名称调用
@timer #语法糖==func2=timer(func2)
def func2():
    time.sleep(5)
    print('in func2')
func2()
#还是原来的调用方式 我们直接得到
#in func2
#5.003789186477661

#带参数的装饰器
### Python 装饰器语法糖使用方法 Python 中的装饰器通过 `@` 符号来简化函数或类的修饰过程。这种语法糖不仅提高了代码的可读性简洁度,而且使得功能扩展更加直观。 #### 基本装饰器示例 当想要增强某个函数的功能而不改变其原有定义时,可以利用装饰器。下面展示了一个简单装饰器的应用: ```python def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() ``` 这段代码展示了如何使用 `@` 语法糖将 `say_hello()` 函数传递给 `my_decorator()` 进行封装[^3]。 #### 参数化的装饰器 如果希望装饰器能够接收参数,则可以通过嵌套一层闭包结构实现更为灵活的功能定制: ```python import functools def repeat(num_times): def decorator_repeat(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(num_times): value = func(*args, **kwargs) return value return wrapper return decorator_repeat @repeat(num_times=4) def greet(name): print(f"Hello {name}") greet("Alice") ``` 此例子中,`repeat()` 是一个带有参数的高阶装饰器,它可以控制目标函数被执行的具体次数[^1]。 #### 类装饰器应用 除了普通的函数装饰器外,Python 同样允许使用类作为装饰器对象。此类需重写 `__call__` 方法以便能够在调用时生效: ```python class CountCalls: def __init__(self, func): self.func = func self.num_calls = 0 def __call__(self, *args, **kwargs): self.num_calls += 1 print(f"This is call #{self.num_calls} of {self.func.__name__!r}") return self.func(*args, **kwargs) @CountCalls def say_goodbye(person="world"): print(f"Goodbye, {person}") say_goodbye() say_goodbye("Bob") ``` 上述代码片段说明了怎样构建并运用基于类形式的计数型装饰器[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值