Python 如何向username=password这样的函数输入参数?

Python 如何向username=password这样的函数输入参数?,python,Python,我希望我的代码是这样的,并使用用户名和密码参数 在代码中作为字符串 def check_registration_rules(username='password'): 调用如下函数: check_registration_rules(parsap1378='pass') 更简单、更清晰(更好,IMHO)的解决方案是有两个函数参数,一个用于用户名,一个用于密码 def check_registration_rules(username, password): print(type(u

我希望我的代码是这样的,并使用用户名和密码参数 在代码中作为字符串

def check_registration_rules(username='password'):
调用如下函数:

check_registration_rules(parsap1378='pass')
更简单、更清晰(更好,IMHO)的解决方案是有两个函数参数,一个用于用户名,一个用于密码

def check_registration_rules(username, password):
    print(type(username), username)  # <class 'str'> parsap1378
    print(type(password), password)  # <class 'str'> pass

check_registration_rules("parsap1378", "pass")
如果要向函数传递其他参数,如果它们不是
key=val
,则需要在关键字参数之前传递它,如文档中所述:


使用
kwargs
的第二个解决方案实际上非常好,因为首先它匹配OP的结构,其次如果需要或不需要,它允许传递多个用户名传递对并同时验证所有…@parsap1378我修改了我的答案。首先,您没有提到您的文档中的多个参数。第二,检查我在回答中提供的关键字参数如何工作。我不知道你所说的“多个参数”是什么意思,但它可以工作,只要你正确使用
kwargs
,它就是所有传递的
key=val
对的
dict
。@Tomerikoo我知道。我是在回应OP的评论,它不适用于多个参数。我只是修改了它,以显示它仍然可以。
def check_registration_rules(**kwargs):
    username, password = kwargs.popitem()
    print(type(username), username)  # <class 'str'> parsap1378
    print(type(password), password)  # <class 'str'> pass

check_registration_rules(parsap1378='pass')
def check_registration_rules(aaa, bbb, **kwargs):
    print(aaa, bbb)  # 111 222

    username, password = kwargs.popitem()
    print(type(username), username)  # <class 'str'> parsap1378
    print(type(password), password)  # <class 'str'> pass

check_registration_rules(111, 222, parsap1378='pass')
def check_registration_rules(**kwargs):
    for username, password in kwargs.items():
        print(type(username), username)
        print(type(password), password)

check_registration_rules(parsap1378='pass', aaa="123", bbb="456")
# <class 'str'> parsap1378
# <class 'str'> pass
# <class 'str'> aaa
# <class 'str'> 123
# <class 'str'> bbb
# <class 'str'> 45