装饰蟒蛇
def our_decorator(func):
def function_wrapper(x):
print("Before calling " + func.__name__)
func(x)
print("After calling " + func.__name__)
return function_wrapper
@our_decorator
def foo(x):
print("Hi, foo has been called with " + str(x))
foo("Hi")
python函数装饰器
#Decorator are just function that take function as first
#parameter and return a function
def logging(f):
def decorator_function(*args, **kwargs):
print('executing '+f.__name__)
return f(*args, **kwargs)
return decorator_function
#Use it like this
@logging
def hello_world():
print('Hello World')
#calling hello_world() prints out:
#executing hello_world
#Hello World
装饰在蟒蛇
# this functon converts any string into uppercase
def deco(function):
def wrap(s):
return s.upper()
function(s)
return wrap
@deco
def display(s):
return s
print(display("not bad"))
蟒蛇的装饰
def deco(func):
def wrap(lst):
x = [1 if i % 2 == 0 else 0 for i in lst]
return x
func(lst)
return wrap
@deco