如何知道我是否正在装饰一种方法

时间:2013-05-18 13:12:55

标签: python python-2.7

当调用装饰器时,mymethod似乎还不是一种方法。

import inspect

class decorator(object):
    def __call__(self, call):
        if inspect.ismethod(call): #Not working yet
            obj = "method"
            args = inspect.getargspec(call)[0][1:]
        elif inspect.isfunction(call):
            obj = "function"
            args = inspect.getargspec(call)[0]
        elif inspect.isclass(call):
            obj = "class"
            args = inspect.getargspec(call.__init__)[0][1:]

        args="(%s)" % repr(args)[1:-1].replace("'","")
        print "Decorate %s %s%s" % (obj, call.__name__, args)
        return call


@decorator()
def myfunction (a,b): pass

@decorator()
class myclass():
    def __init__(self, a, b): pass

    @decorator()
    def mymethod(self, a, b): pass

if inspect.isfunction(myclass.mymethod):
    print "mymethod is a function"
if inspect.ismethod(myclass.mymethod):
    print "mymethod is a method"

输出:

Decorate function myfunction(a, b)
Decorate function mymethod(self, a, b)
Decorate class myclass(a, b)
mymethod is a method

我知道第一个论点是否是'self',但是会有一个不那么脏的解决方案吗?

修改:为什么?

我想填充一个callables及其参数列表,如果它是一个函数或一个类,我可以传递预期的参数,然后我调用它,但如果它是一个方法,我没有“自我”通过的论据。类似的东西:

import inspect

class ToDo(object):
    calls=[]

    def do(self, **kwargs):
        for call in self.calls:
            if 'self' in call.args:
                print "This will fail."
            args = {}
            for arg in call.args:
                args[arg]=kwargs.get(arg, None)
            call.call(**args)

TODO = ToDo()

class decorator(object):
    def __call__(self, call):
        if inspect.isfunction(call):
            args = inspect.getargspec(call)[0]
        elif inspect.isclass(call):
            args = inspect.getargspec(call.__init__)[0][1:]

        self.call = call
        self.args = args
        TODO.calls.append(self)
        return call

TODO.do(a=1, b=2)

2 个答案:

答案 0 :(得分:1)

你无法真正做到这一点。这是一个例子:

>>> class A(object):
...    pass
...
>>> def foo(x): return 3
...
>>> A.foo = foo
>>> type(foo)
<type 'function'>
>>> type(A.foo)
<type 'instancemethod'>

如您所见,您的装饰者可以应用于foo,因为它是一个功能。但是,您可以简单地创建一个引用该函数的类属性来创建一个装饰方法。

(这个例子来自Python 2.7;我不确定Python 3中是否有任何改变,以使上述行为有所不同。)

答案 1 :(得分:0)

你无法从函数中判断方法,但你可以检查第一个参数是否看起来像self:

def __call__(self, func):
    def new_func(*args, **kw):
        if len(args) and hasattr(args[0], '__dict__') \
                and '__class__' in dir(args[0]) and func.__name__ in dir(args[0])\
                and '__func__' in dir(getattr(args[0], func.__name__))\
                and getattr(args[0], func.__name__).__func__ == self.func:
            return my_func(*args[1:], **kw)
        else:
            return my_func(*args, **kw)

    self.func = new_func
    return new_func

但是那对于嵌套装饰器不起作用 - 下一个装饰器会改变功能并且与self.func的比较不会起作用。

另一种方法 - 检查第一个参数的装饰函数的名称是否为self - 这是 Python中非常强大的约定所以可能足够好:

def __call__(self, func):
    def new_func(*args, **kw):
        if len(inspect.getfullargspec(func).args)\
           and inspect.getfullargspec(func).args[0] == 'self':
            return my_func(*args[1:], **kw)
        else:
            return my_func(*args, **kw)

    self.func = new_func
    return new_func