Python - 在必需参数之前的可选参数

时间:2018-05-26 08:35:12

标签: python python-3.x function logic

def func(a,  b,  c,  config)

我总是需要选择三个中的一个(a,b,c),并且始终需要配置。 它应该像:

func(a="hello", config) 

func(b="hello", config) 

是否可以在所需参数之前放置可选参数?

1 个答案:

答案 0 :(得分:2)

使用默认参数。

import random
def rps():
    num=0 #num is the number of times i want the programme to run while roll<10:
    total=0 #this should be close to 3^10 * 10000, its the result of all the tries added together
    roll = 0
    while num <10001:
        tries=0 #this is how many times the programme has tried to get p1=p2
        p1=random.randint(1,3)
        p2=random.randint(1,3)
        if p1==p2:
            roll = roll+1
        else:
            tries = tries + 1
            roll = 0
        if roll==10:
            print(roll)
            total += roll
            roll=0
        num = num + 1
    print (total/10000)
    print(tries)
rps()

使用字典

def func(config, a = None, b = None, c = None):
    pass
func(config, b="B")

编辑:如果您希望配置始终是最后一个,请将其用作

params = {"config": myConfig, "b": valB}  # you want b here
def func(**params):
    config = params["config"]
    a = params.get("a")
    b = params.get("b")
    c = params.get("c")
func(params)