可变参数(*args,**kw)与参数收集的逆过程
前言:
x = {'a': 1, 'b': 2}
class Wupiao(object):
    DEFAULTS = {}
    def __init__(self,config,bb):
        print(self.__dict__) #{}/
        self.__dict__.update(Wupiao.DEFAULTS, **config)
        # print(self.__dict__) #{'a': 1, 'b': 2}
        self.bb = bb
        # print(self.__dict__) #{'a': 1, 'b': 2, 'bb': 88}
        """
           在创建Solver类的对象(p)的时候,p的__dict__属性中只存储了self.xxx的xxx
           使用了这句code之后,p的__dict__属性中会增加config中对应的key:value
        """
A = Wupiao(x,88)
print(Wupiao.__dict__)
print(A.__dict__)
{'__module__': '__main__', 'DEFAULTS': {}, '__init__': <function Wupiao.__init__ at 0x0000000002383488>, '__dict__': <attribute '__dict__' of 'Wupiao' objects>, '__weakref__': <attribute '__weakref__' of 'Wupiao' objects>, '__doc__': None}
{'a': 1, 'b': 2, 'bb': 88}
- *args:表示普通的参数,也即位置参数(positional arguments),由元组存储
- **kwargs:key word args,则表示关键字参数(keyword arguments),由字典存储
1 def foo(*args, **kwargs): 2 print('args = ', args) 3 print('kwargs = ', kwargs) 4 5 if __name__ == '__main__': 6 foo(1,2,3,4) 7 args = (1, 2, 3, 4) 8 kwargs = {} 9 foo(a=1,b=2,c=3) 10 args = () 11 kwargs = {'b': 2, 'c': 3, 'a': 1} 12 foo(1,2,3,4, a=1,b=2,c=3) 13 args = (1, 2, 3, 4) 14 kwargs = {'b': 2, 'c': 3, 'a': 1} 15 foo('a', 1, None, a=1, b='2', c=3) 16 args = ('a', 1, None) 17 kwargs = {'b': '2', 'c': 3, 'a': 1}
1、*args:位置参数
1.1、*args:将参数组成元组;
def print_params(*args): print(args) >> print_params('Testing') ('Testing', ) >> print_params(1, 2, 3) (1, 2, 3)
1.2、与普通参数的组合使用
def print_params(title, *args): print(title) print(args) >> print_params('Params', 1, 2, 3) Params (1, 2, 3)
2、**kw:关键字参数
将参数组织成字典:
def print_params(x, y, z=3, *parms, **kw): print(x, y, z) print(params) print(kw) >> print_params(1, 2, 3, 5, 6, 7, foo=1, bar=2) 1 2 3 (5, 6, 7) {'foo':1, 'bar':2}
可以使用这样的方法创建字典:
def create_dict(**kw): return kw
3、参数收集的逆过程
def add(x, y): return x+y params = (1, 2) print(*params) print(add(*params)) 1 2 3
同样适用于**kw(关键字参数):
def add(m): return m['a']+m['b'] params = {'a':1,'b':2} print({**params}) print(add({**params})) {'a': 1, 'b': 2} 3
4、*的另一妙用
def foo(*x): print(x) #1、(<generator object <genexpr> at 0x00000000055F3CA8>,) foo(i for i in range(10)) #一个迭代器对象构成的 tuple #2、([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],) foo([i for i in range(10)]) #3、(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) foo(*(i for i in range(10))) #4、(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) foo(*[i for i in range(10)])
5、解决一些问题
如何将4个参数传递给一个只接受3个参数的函数:
def fun(a, b, c): print c fun(1, 2, (3, 4))
def fun(a, b, *c): print c[0] fun(1, 2, 3, 4)
参考1:Python进阶-可变参数(*args,**kw)与参数收集的逆过程
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号