Parameters of the day5 - 05 function of Python study notes - keyword parameters

Variable parameters can be passed in any number of parameters, and are automatically grouped into a tuple when the function is called, and keyword parameters can be passed in any number of parameters carrying parameter names, which are automatically grouped into a dict inside the function.
        >>> def person(name,age,**otherinfo):
        ...     print('name:',name,'age:',age,'Other infomations:',otherinfo)
        ...
        >>> person('张三',20)
        name: 张三 age: 20 Other infomations: {}
        >>> person('Li Si', 70, Birth year=1900, Height=168)
        name: Li Si age: 70 Other infomations: {'Height': 168, 'Birth Year': 1900}
        >>> person('Pharaoh next door', 26, year of birth=1992, height=188, hobby='basketball')
        name: Pharaoh next door age: 26 Other infomations: {'height': 188, 'hobby': 'basketball', 'year of birth': 1992}
Keyword parameters can be used as extension functions. In the above example, both name and age are required parameters, but if you need to add more parameters, you can put these more parameters in the keyword parameters as optional Additional items.
Let’s break down the example of the keyword argument above:
        >>> def person(name,age,**otherinfo):
        ... print('name:',name,'age:',age,'Other infomations:',otherinfo)
        ...
         >>> person( 'Li Si', 70, year of birth=1900, height=168)
        name: Li Si age: 70 Other infomations: {'height': 168, 'year of birth': 1900}  
       
        first group the optional items into a dict, then Convert dict to keyword arguments and pass it in
            >>> oi = {'year of birth': 1900, 'height': 168}
            >>> person('Li Si', 70, year of birth=oi['year of birth'] ,height=oi['height'])
            name: Li Si age: 70 Other infomations: {'height': 168, 'birth year': 1900}
        Simplified writing is:
            >>> oi = {'year of birth': 1900,'height': 168}
            >>> person('Li Si',70,**oi)
            name: Li Si age: 70 Other infomations: { 'Height': 168, 'Birth year': 1900}
           
        **oi means to pass all the key-values ​​of the dict of oi into the otherinfo parameter of the function with keyword arguments, and otherinfo will get a dict, which is oi's A copy, changes to the contents of otherinfo will not affect the oi outside the person function.
       
       

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325237776&siteId=291194637