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

Ako*_*pov 5 python selenium dictionary kwargs

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

我有一个类方法:

def submit_new_account_form(self, **credentials):
...
Run Code Online (Sandbox Code Playgroud)

当我在我的对象的实例上调用它时,如下所示:

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

我收到此错误:

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

Wil*_*sem 6

那是合乎逻辑的:**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'})
    
    Run Code Online (Sandbox Code Playgroud)
  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'})
    
    Run Code Online (Sandbox Code Playgroud)

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

loginpage.submit_new_account_form(first_name='Test', last_name='Test', phone_or_email=temp_email, newpass='1q2w3e4r5t', sex='male')
Run Code Online (Sandbox Code Playgroud)

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