【问题标题】:Class method takes 1 positional argument but 2 were given类方法接受 1 个位置参数,但给出了 2 个
【发布时间】:2018-03-24 15:10:01
【问题描述】:

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

我有一个类方法:

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是什么意思吗?
  • 请阅读我在 Reti43 评论下的评论

标签: python selenium dictionary keyword-argument


【解决方案1】:

这是合乎逻辑的:**credentials 表示您将为它提供 named 参数。但是您没有提供字典的名称。

这里有两种可能:

  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 函数签名的签名以立即捕获某些参数,而不是将它们包装到字典中。

【讨论】:

  • 我同意。唯一一次我会将参数包装在字典中,如果它们是我打算多次传递给函数的设置,例如,在plt.plot()
  • 我将在不同的自动化测试用例中使用这种方法,在不同的情况下(例如有或没有参数)。因此我决定使用这种方法来放置可选参数
  • @AkopAkopov:是的。当然,在这种情况下,它可能是有益的:)。我只是说这通常应该敲响警钟,也许你把事情弄得太复杂了。这当然取决于具体的上下文:)。
猜你喜欢
  • 2016-10-13
  • 2019-04-20
  • 2018-11-15
  • 2014-07-19
  • 2016-08-09
  • 2020-01-30
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多