类方法只接受1个位置参数,但给出了2个。

4
我是一位有用的助手,可以为您翻译文本。
我已经阅读了几个与此问题相似的主题,但我不明白在我的情况下错误是如何抛出的。
我有一个类方法:
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

你知道 **kwargs 是什么意思吗? - Willem Van Onsem
请阅读我在Reti43评论下面的评论。 - Akop Akopov
1个回答

6

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

这里有两种可能性:

  1. you use credentials as a single argument, and pass it the dictionary, like:

    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. you pass the dictionary as named arguments, by putting two asterisks in front:

    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函数签名,以立即捕获特定参数,而不是将它们包装成字典。


1
我同意。唯一需要将参数封装在字典中的情况是它们是某些设置,我打算多次传递给函数,例如在 plt.plot() 中。 - Reti43
1
我将在不同的自动化测试用例中使用此方法,针对不同情况(例如带或不带参数)。因此,我决定采用这种方法来放置可选参数。 - Akop Akopov
@AkopAkopov:是的。当然,有时候会出现这样的情况,这可能是有益的 : )。我只是想说,这通常应该让人想到,也许你把事情搞得太复杂了。当然,这取决于具体的上下文 : )。 - Willem Van Onsem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接