首页 > 解决方案 > Python,如何在类方法中使用@

问题描述

我尝试@在类方法中使用。像这样

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(),它会引发 aexception如下。

回溯(最近一次调用最后一次):TypeError:wrapper() 正好采用 0 个参数(给定 1 个)

您知道为什么会引发此错误以及任何解决方案吗?非常感谢!

标签: python

解决方案


该函数wrapper(**kwargs)只接受命名参数。但是,在实例方法中,self自动作为第一个位置参数传递。由于您的方法不接受位置参数,因此它失败了。

您可以编辑为wrapper(self, **kwargs)或更一般wrapper(*args, **kwargs)的 . 但是,您使用它的方式,不清楚这些参数是什么。


推荐阅读