小编Joe*_* M.的帖子

装饰器和类方法

我无法理解为什么会发生以下情况.我有一个装饰器,它除了检查函数是否是一个方法之外什么都不做.我以为我已经理解了Python中的哪种方法,但很明显,情况并非如此:

import inspect

def deco(f):
    def g(*args):
        print inspect.ismethod(f)
        return f(*args)
    return g

class Adder:
    @deco
    def __call__(self, a):
        return a + 1

class Adder2:
    def __call__(self, a):
        return a + 2
Adder2.__call__ = deco(Adder2.__call__)
Run Code Online (Sandbox Code Playgroud)

现在,运行以下命令:

>>> a = Adder()
>>> a(1)
False
2
>>> a2 = Adder2()
>>> a2(1)    
True
3
Run Code Online (Sandbox Code Playgroud)

我希望这段代码能够打印True两次.

那么,如在Adder2中手动装饰功能并不完全等同于通过@deco功能进行装饰?

有人可以这么高兴并解释为什么会这样吗?

python methods class decorator python-decorators

18
推荐指数
2
解决办法
1139
查看次数

标签 统计

class ×1

decorator ×1

methods ×1

python ×1

python-decorators ×1