账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    请教Python装饰器@嵌套顺序的问题
    35
    0

    请教大家两个Python装饰器@的问题。

    问题一:嵌套。

    1 def Decorator2(plugger2):
    2      plugger2()
    3      print ("Plugger2 内调 here!")
    4 def Decorator3(plugger3):
    5      plugger3()
    6      print ("Plugger3 内调 here!")
    
    7 def DecoratorTesting():
    8      @Decorator2
    9      def plugger2():
    10          print ("Plugger2 外调 here!")
    11          @Decorator3
    12          def plugger3():
    13                print ("Plugger3 外调 here!")

    最终运行DecoratorTesting()结果是:

    Plugger2 外调 here!
    Plugger3 外调 here!
    Plugger3 内调 here!
    Plugger2 内调 here!

    我对DecoratorTesting()这个结果不太理解。当第8行@Decorator2的时候,难道不是应该立即回到第1行打印“内调”吗?当第11行@Decorator3的时候,难道不是应该立即回到第4行打印“内调”吗?为什么结果却是刚才的顺序呢?

    问题二:返回。

    def go_Before(request, follow_up):
        print ("Go to the before yields %s." %(request*2))
    def go_After(request, follow_up):
        print ("Go to the after yields %s." %(follow_up*3))
    
    5 def Filter(before_func, after_func):
    6      def f1(main_func):
    7           def f2(request, follow_up):
    8                 before_result = before_func(request, follow_up)
    9                 if (before_result != None):  return before_result;
    
    10                main_result = main_func(request, follow_up)
    11                if (main_result != None):  return main_result;
    
    12                after_result = after_func(request, follow_up)
    13                if (after_result != None):  return after_result;
    14           return f2
    15      return f1
    
    @Filter(go_Before, go_After)
    def go_Middle(request, follow_up):
        print ("Go to the middle.")

    最终运行go_Middle('@', '#')结果是:

    Go to the before yields @@.
    Go to the middle.
    Go to the after yields ###.

    我对go_Middle()这个结果不太理解。第9行,应该已经彻底返回了。可是为什么还会继续执行第10行和以后的部分呢?

    谢谢了先!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 清酒孤欢ゞ 普通会员 1楼

      在Python中,装饰器是一种特殊类型的函数,它在不修改原代码的情况下,对其他函数或类的行为进行修改。装饰器可以用来实现一些功能,比如记录日志、添加权限检查、计时器、缓存结果等。

      在Python中,装饰器的使用是通过在函数定义前加上@符号来实现的。@符号后面跟着装饰器函数的名称,然后是一个冒号(:)。

      嵌套顺序是指在装饰器函数中定义的参数和返回值之间的顺序。例如,下面的装饰器会返回装饰器函数本身:

      ```python def outer_decorator(func): def wrapper(args, kwargs): print("Before function call") result = func(args, **kwargs) print("After function call") return result return wrapper

      @outer_decorator def say_hello(): print("Hello, World!")

      say_hello() ```

      在这个例子中,outer_decorator函数返回了一个装饰器函数wrapper,wrapper函数在调用say_hello函数之前和之后都会打印一些信息。这就是装饰器的嵌套顺序。

      在装饰器函数中,参数和返回值的顺序并不重要,重要的是装饰器函数的内部逻辑。装饰器函数内部的逻辑决定了它在被调用之前和之后会执行什么操作。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部