gpt4 book ai didi

python - 类方法采用 1 个位置参数,但给出了 2 个

转载 作者:太空狗 更新时间:2023-10-30 00:58:56 24 4
gpt4 key购买 nike

我已经阅读了几个有类似问题的主题,但我不明白在我的情况下会抛出错误。

我有一个类方法:

def submit_new_account_form(self, **credentials):
...

当我像这样在我的对象实例上调用它时:

create_new_account = loginpage.submit_new_account_form(
{'first_name': 'Test', 'last_name': 'Test', 'phone_or_email':
temp_email, 'newpass': '1q2w3e4r5t',
'sex': 'male'})

我收到此错误:

line 22, in test_new_account_succes
'sex': 'male'})
TypeError: submit_new_account_form() takes 1 positional argument but 2 were
given

最佳答案

这是合乎逻辑的:**credentials 意味着您将为其提供命名 参数。但是您没有为字典提供名称。

这里有两种可能:

  1. 您将 credentials 用作单个参数,并将字典传递给它,例如:

    def submit_new_account_form(self, credentials):
    # ...
    pass

    loginpage.submit_new_account_form({'first_name': 'Test', 'last_name': 'Test', 'phone_or_email': temp_email, 'newpass': '1q2w3e4r5t', 'sex': 'male'})
  2. 通过在前面放置两个星号来将字典作为命名参数传递:

    def submit_new_account_form(self, **credentials):
    # ...
    pass

    loginpage.submit_new_account_form(**{'first_name': 'Test', 'last_name': 'Test', 'phone_or_email': temp_email, 'newpass': '1q2w3e4r5t', 'sex': 'male'})

第二种方法等于传递命名参数,例如:

loginpage.submit_new_account_form(first_name='Test', last_name='Test', phone_or_email=temp_email, newpass='1q2w3e4r5t', sex='male')

我认为调用它的最后一种方法是更简洁的语法。此外,它允许您轻松修改 submit_new_account_form 函数签名的签名以立即捕获某些参数,而不是将它们包装到字典中。

关于python - 类方法采用 1 个位置参数,但给出了 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46713685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com