[英]Python, How to use the @ in class method
I try to use the @
in the class method. 我尝试在类方法中使用
@
。 like this 像这样
class Dataset:
@parse_func
def get_next_batch(self):
return self.generator.__next__()
and the parse function like this: 解析函数是这样的:
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
However, when I call dataset.get_next_batch()
, it will raise a exception
as followed. 但是,当我调用
dataset.get_next_batch()
,它将引发如下exception
。
Traceback (most recent call last): TypeError: wrapper() takes exactly 0 arguments (1 given)
追溯(最近一次调用最近):TypeError:wrapper()接受0个参数(给定1个)
Do you know why raise this error and any solution? 您知道为什么会引发此错误以及任何解决方案吗? Thank you very much!
非常感谢你!
The function wrapper(**kwargs)
accepts named arguments only . wrapper(**kwargs)
函数仅接受命名参数 。 However, in instance methods, the self
is automatically passed as the first positional argument. 但是,在实例方法中,
self
会自动作为第一个位置参数传递。 Since your method does not accept positional arguments, it fails. 由于您的方法不接受位置参数,因此它将失败。
You could edit to wrapper(self, **kwargs)
or, more general wrapper(*args, **kwargs)
. 您可以编辑到
wrapper(self, **kwargs)
或更一般的wrapper(*args, **kwargs)
。 However, the way you are using it, it is not clear what those arguments are. 但是,您使用它的方式尚不清楚这些参数是什么。
Just simply change 只是简单地改变
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()
@
symbol mean a decorator function. @
符号表示装饰器功能。 Here, it means parse_func(get_next_batch)
. 在这里,它意味着
parse_func(get_next_batch)
。 So if the wrapper using the keyword params ( **para
), you just want to pass some params to the wrapper but you don't actually except for the self
args. 因此,如果包装器使用关键字params(
**para
),则只想将一些参数传递给包装器,但是除了self
args之外,您实际上不需要。 So here I replace the params to positional params *para
. 所以在这里我将参数替换为位置参数
*para
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.