[英]how to input arguments to a function like username=password?
我希望我的代碼像這樣,並在代碼中同時使用用戶名和密碼參數作為字符串。
def check_registration_rules(username='password'):
調用函數是這樣的:
check_registration_rules(parsap1378='pass')
更簡單,更清晰(更好的IMHO)解決方案是具有2個功能參數,其中1個用於用戶名,而1個用於密碼。
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")
但是,如果您真的想像parsap1378='pass'
一樣傳遞它,則可以使用關鍵字arguments :
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')
如果要將其他參數傳遞給函數,如果它們的格式不是key=val
,則需要在關鍵字參數之前傳遞它,如關鍵字arguments docs中所述:
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')
如果要傳遞多個username=password
對,則需要像常規dict
一樣遍歷kwargs
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.