gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:04:17 26 4
gpt4 key购买 nike

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

但是,当我稍微尝试一下时,我只会得到返回绑定(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com