【问题标题】:Function expects 2 arguments when should only one函数在应该只有一个时需要 2 个参数
【发布时间】:2011-03-13 01:37:11
【问题描述】:

我有这样一个函数friend_exists

def friend_exists(request, pid):
    result = False
    try:
        user = Friend.objects.get(pid=pid)
    except Friend.DoesNotExist:
        pass  
    if user:
        result = True

    return result

我从我的其他函数中调用它,如下所示:

exists = friend_exists(form.cleaned_data['pid'])

在哪里pid = u'12345678'。为什么我得到:

Exception Type: TypeError at /user/register/
Exception Value: friend_exists() takes exactly 2 arguments (1 given)

有什么想法吗?

【问题讨论】:

  • 请修正帖子标题错字功能。

标签: python django function argument-passing


【解决方案1】:

为什么你认为它应该只需要一个?您显然在函数定义中有两个参数:

def friend_exists(request, pid):

它在那里说它需要requestpid

【讨论】:

  • 如果这是 friend_exists 函数的实际来源,则看起来不需要 request 参数。也许一个论点是重构(或其他)之后的一些意外保留?
  • 我只是认为请求是自动填充的
【解决方案2】:

它有两个参数,而你只给它一个,form.cleaned_data['pid'] 的值。如果该值实际上是两个参数的元组/列表,您希望使用星号扩展它,例如:

exists = friend_exists(*form.cleaned_data['pid'])

在这种情况下,一种更简洁的方法可能是:

request, pid = form.cleaned_data['pid']
exists = friend_exists(request, pid)

【讨论】:

    【解决方案3】:

    这看起来像 django,所以正确调用函数的方法是 friend_exists(request, form.cleaned_data['pid']。当调用视图函数时,请求会自动填充,因此 django 应用程序中的每次调用似乎都应该发生这种情况,但是当您手动调用该函数时,您必须手动将 request 对象传递给它.

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2014-09-04
      • 2021-04-02
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多