상세 컨텐츠

본문 제목

클래스 데코레이터 - __call__, __init__

Python

by techbard 2012. 5. 20. 22:24

본문

반응형
http://coreapython.hosting.paran.com/tiphack/Python%20Decorators%20Don't%20Have%20to%20be%20(that)%20Scary%20-%20Siafoo.htm

# __init__ 과 __call__ 의 차이

class foo:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

x = foo(1, 2, 3) # __init__

class goo:
def __call__(self, a, b, c):
self.a = a
self.b = b
self.c = c
x = goo()
x(1, 2, 3) # __call__


# 인스턴스 생성할 때 불리는 __init__, 인스턴스 변수를 실행할 때 불리는 __call__


class I():

def __init__(self):

print("init...")


i = I()


# 결과

init...


class C():

def __call__(self):

print("call...")


c = C()

c()


# 결과

call...


# 생성할 때 초기화 vs 호출할 때 불리는


class A:

def __init__(self):

print("init")

def __call__(self):

print("call")


a = A()

a()


# 결과

init

call


# Decorator


class theDecorator():

def __init__(self, f):

self.f = f


def __call__(self):

print("Entering: ", self.f.__name__, " Decoration")

self.f()

print("Exited: ", self.f.__name__, " Decoration\n")


@theDecorator

def firstFunction():

print("Inside: firstFunction() <- Provided by original function")


print("firstFunction call: ")

firstFunction()


# 결과

firstFunction call: 

Entering:  firstFunction  Decoration

Inside: firstFunction() <- Provided by original function

Exited:  firstFunction  Decoration


# Decorator

class PrintSeparator():

def __init__(self, f):

self.func = f


def __call__(self):

print("=" * 30)

self.func()

print("=" * 30)


@PrintSeparator # 이 클래스의 __init__ 을 실행한다.

def myfunc():

print(list(range(10)))


myfunc() # 데코레이터 클래스의 __call__을 실행한다.


# 결과

==============================

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

==============================


# 데코레이터를 사용하고 함수의 인자까지 처리

import time


class TimeThis():

def __init__(self, f):

self.f = f


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

start = time.time()

self.f(*args, **kwargs)

end = time.time()

print("time: {}".format(end - start))


@TimeThis

def countdown(n):

while n > 0:

n =- 1


countdown(10000000000)


# 결과

time: 2.1457672119140625e-06


반응형

관련글 더보기

댓글 영역