1

I currently have the following code which uses a python library:

f = Foo(original_method, parameters)

I would like to augment original_method, and have a decorator add a few lines of code. Let's call the new decorated method decorated_method. Finally I would like to have something like this:

f = Foo(decorated_method(original_method), parameters)

My questions are: is this possible? how would the decorator look like? I must say that I can't extend original_method, since it is part of an external library.

Edit: original_method is not executed, is only passed to Foo as a parameter. decorated_method function should do some logging and gather some statistics of the number of calls.

Later edit: the code in examples below works fine. I had a few additional problems because original_method had a few attributes, so this is the final code:

def decorated_method(method):

    def _reporter(*args, **kwargs):
        addmetric('apicall', method.__name__)
        return method(*args, **kwargs)

    _reporter.original_method_attribute = method.original_method_attribute
    return _reporter
4

2 に答える 2

2

やりたいことについては言及していませんdecorated_methodが、これは確かに可能です:

def decorated_method(f):
    def _wrapped(*args, **kwargs):
        print "About to call f!"
        ret = f(*args, **kwargs)
        print "Just got finished with f, ret = %r" % (ret,)
        return ret
    return _wrapped

これは単なる標準的なデコレーター構造です。デコレーターは、関数を受け取り、関数を返す関数です。

于 2012-07-11T11:04:50.050 に答える
0

絶対:

def decorated_method(fn):
    def inner_method(*args, **kwargs):
        print("before calling")
        result = fn(*args, **kwargs)
        print("after calling")
        return result
    return inner_method

これが機能するようになったら、signature-preserving decoratorsを確認する必要があります。

于 2012-07-11T11:05:48.163 に答える