简体   繁体   English

如何从装饰器函数执行类方法

[英]How to execute a Class method from decorator function

I have a class with a main dictionary self.wardrobe , which is being saved to a JSON file by the method: self.save() .我有一个带有主字典self.wardrobe的类,它通过以下方法保存到 JSON 文件: self.save()

I am now trying to make a decorator which calls the self.save() , method after executing the decorated method.我现在正在尝试制作一个装饰器,它在执行装饰方法后调用self.save()方法。

Thanks in advance:)提前致谢:)

Edit:编辑:

This is a try defining the decorator outside of the class (I also tried @staticmethod but it didn't work somehow):这是在类之外定义装饰器的尝试(我也尝试过@staticmethod但不知何故它不起作用):

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

Second Edit:第二次编辑:

this is the part of the class important for this problem:这是对这个问题很重要的类的一部分:

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)

Summary: I want to create a decorator for the method duplicate() , which executes the method save() right after.摘要:我想为方法duplicate()创建一个装饰器,它会在之后立即执行方法save()

(of course I have other functions than duplicate() , which need to save afterwards too. thats why I dont just call save() in the method.) (当然除了duplicate()我还有其他功能,这些功能也需要在之后保存。这就是为什么我不只是在方法中调用save()的原因。)

When decorating a method self is the first argument passed to inner.装饰方法时, self是传递给 inner 的第一个参数。 You could do something like:你可以这样做:

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)

Input json:输入json:

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

Output json:输出json:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM