簡體   English   中英

缺少必需的位置參數:Python: self

[英]missing required positional arguments: Python: self

得到一個錯誤:

TypeError: _get_request() missing 6 required positional arguments: 'id_list', 'id_item', 'to_be_sent', 'open', 'received', and 'sent'

當我嘗試調用該函數時:

def _get_request(self, id: str,
                           id_list: List[str],
                           id_item: List[int],
                           to_be_sent: List[int],
                           open: List[int],
                           received: List[int],
                           sent: List[int]):



    return {
            'id': user_id,
            'num_results': 3,
            'id_list': uniqueVisitId,
            'id_item': id_item,
            'to_be_sent': need_to_be_sent,
            'open': open,
            'received': received,
            'sent': sent
    }

經過:

self._get_request(
          {
           'id': 'x',
            'id_list': ['a', 'x'],
            'id_item': [1, 2],
            'to_be_sent': [1, 0],
            'open': [0, 0],
            'received': [0, 0],
            'sent': [0, 0]
          }
     )

任何猜測為什么我的函數無法識別我傳遞的位置參數?

因為你傳遞的是字典而不是參數......

您應該在沒有 Dict 語法的情況下按順序傳遞參數:

self._get_request('x', ['a', 'x'], [1, 2],  [1, 0],   [0, 0],[0, 0], [0, 0])

在 dict 項之前使用**將它們解析為函數中的 key=value

def foo(*, a, b):
    return a, b


dict = {'a': 1, 'b': 2}
print(foo(dict)) # -> missing
print(foo(**dict)) # -> returns (1, 2)

你只傳遞了一個參數——一本字典。 如果您只是編寫對 get_request() 的特定調用,和/或字典將始終具有該組指定的鍵,請執行 adir 所說的操作。 如果您傳遞的字典來自其他地方,並且可能有不同的關鍵字。 那么你可以像這樣使用字典解包:

# Assigning it just for the example, might be the result from a function or whatever you're doing
request_info_dict = {
                     'id': 'x',
                     'id_list': ['a', 'x'],
                     'id_item': [1, 2],
                     'to_be_sent': [1, 0],
                     'open': [0, 0],
                     'received': [0, 0],
                     'sent': [0, 0]
                   }
self._get_request(**request_info_dict)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM