def outer_function():
print "1. This is outer function!"
def inner_function():
print "2. This is inner function, inside outer function!"
print "3. This is outside inner function, inside outer function!"
return inner_function()
func_assign = outer_function()
#######################Output######################################
1. This is outer function!
3. This is outside inner function, inside outer function!
2. This is inner function, inside outer function!
#!/usr/bin/python3
from functools import wraps
def decorator(func):
"""decorator docstring is here!"""
@wraps(func)
def inner(*args):
"""inner docstring is here!"""
print(func.__name__+' was called')
return func(*args)
return inner
@decorator
def func(x):
"""Trible times"""
return x**3
print(func(3))
print(func.__name__)
print(func.__doc__)
#####################################output###############################
func was called
27
func
Trible times
七.向装饰器传递参数
#!/usr/bin/python3
class Decorator(object):
def __init__(self, arg1, arg2):
print('参数传递给装饰器类,分别为:{0} and {1}'.format(arg1, arg2))
self.arg1 = arg1
self.arg2 = arg2
def __call__(self, func, *args, **kwargs):
def inner(*args, **kwargs):
print('参数传递给内部方法:%s and %s' % (self.arg1, self.arg2))
return func(*args, **kwargs)
return inner
@Decorator('kobe', 'Brany')
def print_(*args):
for arg in args:
print(arg, end='')
print_(1,2,3)
参数传递给装饰器类,分别为:kobe and Brany
参数传递给内部方法:kobe and Brany
123
decor
A function definition may be wrapped by one or more expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code: