zoukankan      html  css  js  c++  java
  • 装饰器(带参数)

    如果明白装饰器的原理那么带参数的装饰器就很容易理解了

    代码:

    def s1(func):
        def inner(a,b):    #f1=inner(a,b) 接受2个参数,然后在把2个参数传递给func(a,b)
            print("hello")
            r =func(a,b)
            print("word")
    
            return r
        return inner
    @s1
    def f1(a,b):
        print(a+b)
    
    
        
    f1(20,50)

    现在有个问题如果装饰的函数有的参数是1个有的是2个怎么办?

    @s1
    def f1(a):
        print(a+b)
    
    
    @s1
    def f2(a,b):
        print(a+b)
    
    @s1
    def f3(a,b,c):
        print(a+b) 

    解决这个很简单:

    def s1(func):
        def inner(*args,**kwargs):  #接受万能参数
            print("hello")
            r =func(*args,**kwargs) #这样写可以把参数对应到底层函数的形参数量。比如*args接受参数后是元组(10,20),f2(a,b)  args会自动将元组拆解开。
    #等同于这样f3(10,20)
    print("word") return r return inner @s1 def f1(a): print(a) @s1 def f2(a,b): print(a,b) @s1 def f3(a,b,c):a print a,b,c f1("f1===a") #传递一个参数 f2(10,20) #传递2个参数 f3(11,22,{"aa":"bb"}) #传递三个参数
  • 相关阅读:
    与HDFS交互- By java API编程
    与HDFS交互- By web界面
    与HDFS交互-By shell命令
    hadoop下HDFS基本命令使用
    ubuntu安装hadoop经验
    HTTP状态码了解
    软件需求与分析
    软件需求与分析
    软件需求与分析
    浪潮之巅
  • 原文地址:https://www.cnblogs.com/menkeyi/p/6730662.html
Copyright © 2011-2022 走看看