Skip to main content
 首页 » 编程设计

oop之指定要在许多函数结束时执行的操作

2025年05月04日32sharpest

我有一个 python 对象,其中一堆函数需要在执行结束时执行相同的操作,就在 return 语句之前。例如:

def MyClass(object): 
    def __init__(self): 
        pass 
 
    def update_everything(self): 
        '''update everything''' 
        pass 
 
    def f1(self): 
        #do stuff 
        self.update_everything() 
        return result 
 
    def f2(self): 
        #do stuff 
        self.update_everything() 
        return result 
 
    def f3(self): 
        #do stuff 
        self.update_everything() 
        return result 

除了在每个函数末尾的显式调用之外,最好的(pythonic?)方法是什么?

请您参考如下方法:

我认为您的问题的任何解决方案都是非 Python 的,因为(正如 Tim Peters 在 Python 之禅 (import this) 中所说):

Explicit is better than implicit.