zoukankan      html  css  js  c++  java
  • 函数参数

    # 关键字参数
    def menu(wine, entree, dessert):
        print({'wine': wine, 'entree': entree, 'dessert': dessert})
    
    
    menu('frontenac', dessert='flan', entree='fish')
    # 指定默认参数值
    def menu(wine, entree, dessert='pudding'):
        print({'wine': wine, 'entree': entree, 'dessert': dessert})
    
    menu('chardonnay', 'chicken') # {'dessert': 'pudding', 'entree': 'chicken', 'wine': 'chardonnay'}
    
    def nonbuggy(arg, result=None):
        if result is None:
            result = []
        result.append(arg)
        print(result)
    
    nonbuggy('a') # ['a']
    nonbuggy('b') # ['b']
    # 使用*收集位置参数
    def print_args(*args):
        print(args)
    
    
    print_args(3, 2, 1, 'wait!', 'uh...')
    
    def print_more(required1, required2, *args):
        print('Need this one:', required1)
        print('Need this one too:', required2)
        print('All the rest:', args)
    
    print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
    
    #(3, 2, 1, 'wait!', 'uh...')
    #('Need this one:', 'cap')
    #('Need this one too:', 'gloves')
    #('All the rest:', ('scarf', 'monocle', 'mustache wax'))
    # 使用**收集关键字参数
    #使用两个星号可以将参数收集到一个字典中,
    #参数的名字是字典的键,对应参数的值是字 典的值
    def print_kwargs(**kwargs):
        print(kwargs)
    
    print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
    
    #{'dessert': 'macaroon', 'entree': 'mutton', 'wine': 'merlot'}

    关键词变量

    def get_log(user_id, log_id):
        print(user_id, log_id)
    
    get_log('1', '1')
    get_log(user_id='1', log_id='1')
    parts = {'user_id': '1', 'log_id': '1'}
    get_log(**parts) #等价get_log(user_id='1', log_id='1')
  • 相关阅读:
    试题 E: 迷宫
    对拍程序
    人群中钻出个光头
    HDU-魔咒词典(字符串hash)
    第八集 你明明自己也生病了,却还是要陪着我
    智力问答 50倒计时
    数据结构
    LeetCode刷题 fIRST MISSING POSITIVE
    LeetCode Best to buy and sell stock
    LeetCode Rotatelmage
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5207247.html
Copyright © 2011-2022 走看看