클래스 장식기

5185 단어
우선__call__ 방법.
def func():
    print('hello')


func()
print(func())
#  --->call---> called
#

대응하는, 클래스 실례 대상의 호출은 __call__ 특수한 방법으로 사용해야 한다.
class Student:
    def __init__(self, name):
        self.name = name

    def __call__(self, classmate):
        print(' %s, %s' % (self.name, classmate))

stu = Student('sb')
stu('bc')

클래스로 장식기 구현__init__``__call__ 방법을 통해 실현
class Test:

    def __init__(self, func):
        print(' ')
        self.__func = func

    def __call__(self, *args, **kwargs):
        print('Wrapper Context')
        print('Before')
        self.__func(*args, **kwargs)
        print('After')

@Test
def show():
    print('hello')

print('flag')
show()
# 
#flag
#Wrapper Context
#Before
#hello
#After

좋은 웹페이지 즐겨찾기