Skip to main content
 首页 » 编程设计

python之如何在运行时将参数传递给装饰器

2025年02月15日9开发

我正在使用装饰器进行一些上下文管理,例如文件备份、恢复项目中的排序,并尝试使用装饰器来实现该目的。

但我不明白如何在运行时将参数传递给装饰器。

例如我的类(class)会是这样的:

class myLogFileHandler: 
    def __init__(self,file): 
        self.file=file 
        return 
 
    @copyAndRestoreFile(file=<how-pass-self.file-here?>) 
    def performAction(**kwargs): 
        """ 
           do something 
        """ 

我的装饰器将是:

def copyAndRestoreFile(file): 
    def dec(fn): 
        def wrapper(*args,**kwargs): 
            #copy file to temp... 
            fn(*args,**kwargs) 
            #restore file from temp... 
        return wrapper 
    return dec 

但如您所见,文件名仅在我创建对象时可用。那么如何解决此类问题。

我尝试了几个有效的解决方案:

  1. 使装饰器不带任何参数,并使其在输入参数字典中查找特定变量..

    def copyAndRestoreFile(fn): 
        def dec(**kwargs,file): 
            #copy file to temp... 
            fn(*args,**kwargs) 
            #restore file from temp... 
        return dec   
     
    @copyAndRestoreFile 
    def performAction(**kwargs,file=self.file): 
        """ 
           do something 
        """ 
    

    通过这种方法,我无法使装饰器成为任何人都可以使用的通用装饰器。任何使用它的人都应该为被装饰的函数提供一个文件参数。这就是我所看到的缺点。 ..

  2. 在运行时装饰..

    def performAction(**kwargs): 
        copyAndRestoreFile(file=self.file)(self._actualActionCode)(**kwargs) 
     
    def _actualActionCode(**kwargs): 
        """ 
           do something 
        """ 
    

有没有更好的方法来解决这个问题?

请您参考如下方法:

有关示例,请参见此处 - Passing parameters to decorator at runtime

如果还有其他细节请说明。