簡體   English   中英

Python,如何使用@ in類方法

[英]Python, How to use the @ in class method

我嘗試在類方法中使用@ 像這樣

class Dataset:
  @parse_func
  def get_next_batch(self):
      return self.generator.__next__()

解析函數是這樣的:

def parse_func(load_batch):
  def wrapper(**para):
    batch_files_path, batch_masks_path, batch_label = load_batch(**para)
    batch_images = []
    batch_masks = []
    for (file_path, mask_path) in zip(batch_files_path, batch_masks_path):
        image = cv2.imread(file_path)
        mask = cv2.imread(mask_path)
        batch_images.append(image)
        batch_masks.append(mask)
    return np.asarray(batch_images, np.float32), np.asarray(batch_masks, np.uint8), batch_label

  return wrapper

但是,當我調用dataset.get_next_batch() ,它將引發如下exception

追溯(最近一次調用最近):TypeError:wrapper()接受0個參數(給定1個)

您知道為什么會引發此錯誤以及任何解決方案嗎? 非常感謝你!

wrapper(**kwargs) 函數僅接受命名參數 但是,在實例方法中, self自動作為第一個位置參數傳遞。 由於您的方法不接受位置參數,因此它將失敗。

您可以編輯到wrapper(self, **kwargs)或更一般的wrapper(*args, **kwargs) 但是,您使用它的方式尚不清楚這些參數是什么。

只是簡單地改變

def parse_func(load_batch):
  def wrapper(*para):
    batch_files_path, batch_masks_path, batch_label = load_batch(*para)
    batch_images = []
    batch_masks = []
    for (file_path, mask_path) in zip(batch_files_path, batch_masks_path):
        image = cv2.imread(file_path)
        mask = cv2.imread(mask_path)
        batch_images.append(image)
        batch_masks.append(mask)
    return np.asarray(batch_images, np.float32), np.asarray(batch_masks, np.uint8), batch_label

  return wrapper()

@符號表示裝飾器功能。 在這里,它意味着parse_func(get_next_batch) 因此,如果包裝器使用關鍵字params( **para ),則只想將一些參數傳遞給包裝器,但是除了self args之外,您實際上不需要。 所以在這里我將參數替換為位置參數*para

暫無
暫無

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

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