program story

데코레이터에서 자신에 액세스

inputbox 2020. 11. 15. 11:15
반응형

데코레이터에서 자신에 액세스


unittest의 setUp () 메서드에서 나중에 실제 테스트에서 참조되는 몇 가지 자체 변수를 설정했습니다 . 로깅을 수행하는 데코레이터도 만들었습니다. 데코레이터에서 자체 변수에 액세스 할 수있는 방법이 있습니까?

간단하게하기 위해 다음 코드를 게시합니다.

def decorator(func):
    def _decorator(*args, **kwargs):
        # access a from TestSample
        func(*args, **kwargs)
    return _decorator

class TestSample(unittest.TestCase):    
    def setUp(self):
        self.a = 10

    def tearDown(self):
        # tear down code

    @decorator
    def test_a(self):
        # testing code goes here

데코레이터에서 (setUp ()에 설정) 액세스 하는 가장 좋은 방법은 무엇입니까 ?


메서드를 데코레이션하고 self있고 메서드 인수이므로 데코레이터는 self런타임에에 액세스 할 수 있습니다. 아직 객체가 없기 때문에 구문 분석 시간에는 분명히 아닙니다.

따라서 데코레이터를 다음과 같이 변경합니다.

def decorator(func):
    def _decorator(self, *args, **kwargs):
        # access a from TestSample
        print 'self is %s' % self
        func(self, *args, **kwargs)
    return _decorator

참고 URL : https://stackoverflow.com/questions/7590682/access-self-from-decorator

반응형