python - 为什么 Python 类方法装饰器不接收该方法作为绑定(bind)方法?

标签 python

当我为类方法创建装饰器时,它总是接收“function”类型的方法。

但是,当我稍微尝试一下时,我只得到了绑定(bind)方法:

class Test(object):
    def save(self):
        print "Save called"
    def func(self):
        print "Func called"

然后:

>>> type(Test.func)
<type 'instancemethod'>
>>> type(Test().func)
<type 'instancemethod'>

我最终想做的是创建一个类方法装饰器,它还装饰同一个类上的一些其他方法。我该如何去做呢?

最佳答案

这是不可能的;您必须使用类装饰器或元类来代替。装饰器语法

class Foo(object):
    @dec
    def bar(self): pass

表示

class Foo(object)
    def bar(self): pass
    bar = dec(bar)

其中 class 定义的处理方式如下:执行主体,然后收集定义并将它们包装在 class 对象中。即,装饰是在出现之前完成的。

关于python - 为什么 Python 类方法装饰器不接收该方法作为绑定(bind)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7484501/

相关文章:

python - ipywidgets 文本区域 on_submit()

python - 不可变字典,仅用作另一个字典的键

javascript - 如何渲染JS为cookie生成指纹?

python - 如何在python服务器中保存视频的<httpfile>

python - conda 更新导致 ImportError : No module named tqdm

python - 如何让 Python XMLGenerator 输出 CDATA

python - 处理具有几乎相似记录但时间不同的 csv 文件 - 需要将它们分组为一条记录

python - diff算法的python实现

python - Python中的最大 float 是多少?

Python 作业——创建一个新列表