如何从decorator函数执行Class方法



我有一个主字典self.wardrobe的类,它被保存到一个JSON文件的方法:self.save()

我现在正试图使一个decorator调用self.save(),方法后执行装饰的方法。

Thanks in advance:)

编辑:

这是一个尝试定义类之外的装饰器(我也尝试了@staticmethod,但它没有工作):

def decorate_save(func):
def inner(*args, **kwargs):
val = func(*args, **kwargs)
self.save()
return val
return inner()
<标题>

第二个编辑:

这是类中对这个问题很重要的部分:

class Wardrobe:
def __init__(self, filepath):
self.filepath = filepath
with open(self.filepath, 'r') as f:
self.wardrobe = json.load(f)
# self.wardobe is a dict
def duplicate(self, index: int):
item = self.wardrobe['all'][index]
self.wardrobe['all'].append(item) # self.wardrobe['all'] is a list
def save(self):
with open(self.filepath, 'w') as f:
json.dump(self.wardrobe, f, indent=4)

总结:我想为方法duplicate()创建一个装饰器,它紧接着执行方法save()

(当然我有其他功能比duplicate(),这需要保存之后。这就是为什么我不直接在方法中调用save()

修饰方法时,self是传递给inner的第一个参数。你可以这样做:

import json
def decorate_save(method):
def inner(self, *args, **kwargs):
val = method(self, *args, **kwargs)
self.save()
return val
return inner
class Wardrobe:
def __init__(self, filepath):
self.filepath = filepath
with open(self.filepath, 'r') as f:
self.wardrobe = json.load(f)
# self.wardobe is a dict
@decorate_save
def duplicate(self, index: int):
item = self.wardrobe['all'][index]
self.wardrobe['all'].append(item) # self.wardrobe['all'] is a list
def save(self):
with open(self.filepath, 'w') as f:
json.dump(self.wardrobe, f, indent=4)
w = Wardrobe('input_nogit.json')
w.duplicate(1)

输入json:

{
"all": [
"socks",
"sandals"
]
}

输出json:

{
"all": [
"socks",
"sandals",
"sandals"
]
}

最新更新