在每个方法运行后更改 class 中的实例变量的最干净方法?

Cleanest way to change instance variable in class after each method runs?

假设我想在 class 中的每个方法 运行 之后更改一个实例变量。做这个的最好方式是什么?我知道如何使用装饰器(在非常基本的级别),但不知道如何使用它们修改 class 中的实例变量。

例如,我想实现如下所示,但没有从每个方法

中显式调用 post_method_routine
class MyClass():
    def __init__(self):
        self.state = True

    def post_method_routine(self):
        self.state = False
        print(self.state)

    def method1(self):
        # do stuff
        self.post_method_routine()

    def method2(self):
        # do stuff
        self.post_method_routine()

    def methodN(self):
        # do stuff
        self.post_method_routine()

myinst = MyClass()
myinst.method1() # Output: False

装饰器是解决这个问题的干净方法

def post_method(fn):
    def __inner(self,*args,**kwargs):
        result = fn(*args,**kwargs)
        self.post_method_routine()
        return result
    return __inner

现在就用那个...但我不知道你这样做的真正目的是什么

class MyClass():
    def __init__(self):
        self.state = True

    def post_method_routine(self):
        self.state = False
        print(self.state)

    @post_method
    def method1(self):
        # do stuff

    @post_method    
    def method2(self):
        # do stuff

如果您想自动将它应用到所有以 method 开头的方法,您可以这样做

class MyClass():
    def __init__(self):
        self.state = True

    def post_method_routine(self):
        self.state = False

    def method1(self):
        # do stuff

    def method2(self):
        # do stuff

for method_name in dir(MyClass):
    if method_name.startswith("method"):
        setattr(MyClass,method_name,post_method(getattr(MyClass,method_name)))

但是我强烈不鼓励这样做,因为对于不经意的观察者来说"magic"