[python] 클래스의 파이썬 데코레이터

다음과 같은 것을 쓸 수 있습니까?

class Test(object):
    def _decorator(self, foo):
        foo()

    @self._decorator
    def bar(self):
        pass

이것은 실패합니다 : @self의 self는 알 수 없습니다

나는 또한 시도했다 :

@Test._decorator(self)

또한 실패 : 테스트 알 수 없음

데코레이터에서 일부 인스턴스 변수를 임시로 변경 한 다음 데코 레이팅 된 메소드를 다시 변경하기 전에 실행하고 싶습니다.



답변

이와 같은 것이 필요한 일을합니까?

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

test = Test()

test.bar()

이렇게하면 데코레이터에 액세스하기 위해 self를 호출하지 않고 일반 네임 스페이스로 클래스 네임 스페이스에 숨겨집니다.

>>> import stackoverflow
>>> test = stackoverflow.Test()
>>> test.bar()
start magic
normal call
end magic
>>> 

의견의 질문에 답변하기 위해 편집 :

다른 클래스에서 숨겨진 데코레이터를 사용하는 방법

class Test(object):
    def _decorator(foo):
        def magic( self ) :
            print "start magic"
            foo( self )
            print "end magic"
        return magic

    @_decorator
    def bar( self ) :
        print "normal call"

    _decorator = staticmethod( _decorator )

class TestB( Test ):
    @Test._decorator
    def bar( self ):
        print "override bar in"
        super( TestB, self ).bar()
        print "override bar out"

print "Normal:"
test = Test()
test.bar()
print

print "Inherited:"
b = TestB()
b.bar()
print

산출:

Normal:
start magic
normal call
end magic

Inherited:
start magic
override bar in
start magic
normal call
end magic
override bar out
end magic


답변

당신이하고 싶은 것은 불가능합니다. 예를 들어 아래 코드가 유효한지 여부를 확인하십시오.

class Test(object):

    def _decorator(self, foo):
        foo()

    def bar(self):
        pass
    bar = self._decorator(bar)

물론 self해당 시점에서 정의 되지 않았으므로 유효하지 않습니다 . Test클래스 자체가 정의 될 때까지 정의되지 않을 때 와 동일 합니다 (과정 중). 데코레이터 스 니펫이 변환되는 코드이기 때문에이 코드 스 니펫을 보여 드리겠습니다 .

보시다시피, 데코레이터에서 인스턴스에 액세스하는 것은 실제로 가능하지 않습니다. 데코레이터는 인스턴스화 중이 아닌 연결된 함수 / 메소드를 정의하는 동안 적용되기 때문에 불가능합니다.

클래스 수준의 액세스 가 필요한 경우 다음을 시도하십시오.

class Test(object):

    @classmethod
    def _decorator(cls, foo):
        foo()

    def bar(self):
        pass
Test.bar = Test._decorator(Test.bar)


답변

import functools


class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)


e = Example()
e.method()


답변

일부 디버깅 상황 에서이 유형의 데코레이터를 사용하면 호출 함수를 찾을 필요없이 장식하여 클래스 속성을 재정의 할 수 있습니다.

class myclass(object):
    def __init__(self):
        self.property = "HELLO"

    @adecorator(property="GOODBYE")
    def method(self):
        print self.property

여기 데코레이터 코드가 있습니다

class adecorator (object):
    def __init__ (self, *args, **kwargs):
        # store arguments passed to the decorator
        self.args = args
        self.kwargs = kwargs

    def __call__(self, func):
        def newf(*args, **kwargs):

            #the 'self' for a method function is passed as args[0]
            slf = args[0]

            # replace and store the attributes
            saved = {}
            for k,v in self.kwargs.items():
                if hasattr(slf, k):
                    saved[k] = getattr(slf,k)
                    setattr(slf, k, v)

            # call the method
            ret = func(*args, **kwargs)

            #put things back
            for k,v in saved.items():
                setattr(slf, k, v)

            return ret
        newf.__doc__ = func.__doc__
        return newf 

참고 : 클래스 데코레이터를 사용했기 때문에 데코레이터 클래스 생성자에 인수를 전달하지 않더라도 함수를 장식하기 위해 괄호와 함께 @adecorator ()를 사용해야 합니다.


답변

이것은 같은 클래스 내에 정의 된 내부 self에서 액세스하고 사용하는 한 가지 방법입니다 decorator.

class Thing(object):
    def __init__(self, name):
        self.name = name

    def debug_name(function):
        def debug_wrapper(*args):
            self = args[0]
            print 'self.name = ' + self.name
            print 'running function {}()'.format(function.__name__)
            function(*args)
            print 'self.name = ' + self.name
        return debug_wrapper

    @debug_name
    def set_name(self, new_name):
        self.name = new_name

출력 (에서 테스트 Python 2.7.10) :

>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'

위의 예제는 바보이지만 작동합니다.


답변

나는 매우 비슷한 문제를 연구 하면서이 질문을 발견했습니다. 내 해결책은 문제를 두 부분으로 나누는 것입니다. 먼저, 클래스 메소드와 연관시킬 데이터를 캡처해야합니다. 이 경우 handler_for는 Unix 명령을 해당 명령의 출력에 대한 핸들러와 연결합니다.

class OutputAnalysis(object):
    "analyze the output of diagnostic commands"
    def handler_for(name):
        "decorator to associate a function with a command"
        def wrapper(func):
            func.handler_for = name
            return func
        return wrapper
    # associate mount_p with 'mount_-p.txt'
    @handler_for('mount -p')
    def mount_p(self, slurped):
        pass

이제 각 클래스 메소드와 일부 데이터를 연관 시켰으므로 해당 데이터를 수집하여 클래스 속성에 저장해야합니다.

OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
    try:
        OutputAnalysis.cmd_handler[value.handler_for] = value
    except AttributeError:
        pass


답변

다음은 Michael Speer의 답변을 확장하여 몇 단계 더 나아가는 것입니다.

인수를 가져 와서 인수와 반환 값이있는 함수에 작용하는 인스턴스 메소드 데코레이터.

class Test(object):
    "Prints if x == y. Throws an error otherwise."
    def __init__(self, x):
        self.x = x

    def _outer_decorator(y):
        def _decorator(foo):
            def magic(self, *args, **kwargs) :
                print("start magic")
                if self.x == y:
                    return foo(self, *args, **kwargs)
                else:
                    raise ValueError("x ({}) != y ({})".format(self.x, y))
                print("end magic")
            return magic

        return _decorator

    @_outer_decorator(y=3)
    def bar(self, *args, **kwargs) :
        print("normal call")
        print("args: {}".format(args))
        print("kwargs: {}".format(kwargs))

        return 27

그리고

In [2]:

    test = Test(3)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )
    
    start magic
    normal call
    args: (13, 'Test')
    kwargs: {'q': 9, 'lollipop': [1, 2, 3]}
Out[2]:
    27
In [3]:

    test = Test(4)
    test.bar(
        13,
        'Test',
        q=9,
        lollipop=[1,2,3]
    )
    
    start magic
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-3-576146b3d37e> in <module>()
          4     'Test',
          5     q=9,
    ----> 6     lollipop=[1,2,3]
          7 )

    <ipython-input-1-428f22ac6c9b> in magic(self, *args, **kwargs)
         11                     return foo(self, *args, **kwargs)
         12                 else:
    ---> 13                     raise ValueError("x ({}) != y ({})".format(self.x, y))
         14                 print("end magic")
         15             return magic

    ValueError: x (4) != y (3)