Python成员函数装饰器使用实例作为参数

标签 python

如何在 python 成员函数装饰器中使用实例作为参数。 下面是一个例子。

def foo(func):
    def wrap(s):
        func()
        s.ma()
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo(self)     #error.name 'self' is not defined
    def mb(self):
        print "this is mb"

最佳答案

不清楚您在寻找什么,但是如果您希望能够在装饰器中使用对实例的引用:

def foo(func):
    def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance

        func(s) # This is a function, not a method yet - so we need to pass in the reference

        s.ma() # This is a method, because you use attribute lookup on the object s to get it
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args here
    def mb(self):
        print "this is mb"

我认为您在这里对 Python 中的方法和函数之间的区别感到困惑 – 您似乎期望 func 会像方法一样工作,但实际上它仍然是一个函数正在装修。装饰函数将在实例的属性查找中转换为方法;这意味着当您在包装函数中调用 func 时,您仍然需要显式 self。

查看 How to make a chain of function decorators? 的绝妙答案以便更好地解释正在发生的事情。

关于Python成员函数装饰器使用实例作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14745223/

相关文章:

python - 用Python挖掘海量数据集

python - 一次迭代多个列表的最佳方法是什么?

python - Pandas-根据重叠时间段分割数据集

python - 使用 Python 提交表单后在浏览器中显示网站

python - 如何从 ipdb 中分配给 ipython 全局命名空间?

python - 模拟将 UUID 编码为 Base64

python - Python 中的 TCP 发送错误 - 套接字的协议(protocol)类型错误

python - opencv图像编码返回数组,而不是缓冲区

python - 如何使用包含可选模型的元组定义嵌套 Pydantic 模型?

python - 从 python 字典中的列表中检索值时遇到问题