类方法需要1个位置参数,但有2个被给出

问题描述:

我已经阅读了几个类似问题的主题,但我不明白在我的情况下引发的错误。类方法需要1个位置参数,但有2个被给出

我有一类方法:

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 
+0

你知道'** kwargs'的含义吗? –

+0

请阅读我对Reti43评论的评论 –

好这是合乎逻辑的:**credentials意味着您将提供它名为 a rguments。但是你不提供字典的名字。

这里有两种可能性:

  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') 

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

+1

我同意。唯一一次,我将包装在字典中的参数,如果他们的设置,我打算传递给多次函数,例如'plt.plot()' – Reti43

+1

我将在不同的自动化测试用例中使用此方法,不同的情况下(例如有或没有参数)。因此,我决定使用这种方法来将可选参数 –

+0

@AkopAkopov:是的。当然可以有这样的情况下,这可能是有益的:)。我只是说这通常应该是一个钟声,也许你让事情变得复杂。这当然取决于具体的背景:)。 –