python方法装饰器、静态方法

1、装饰器

>>> def now():
...     print '2013-12-25'
...
>>> f = now
>>> f()
2013-12-25

假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。

本质上,decorator就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:

def log(func):
    def wrapper(*args, **kw):
        print 'call %s():' % func.__name__
        return func(*args, **kw)
    return wrapper
@log
def now():
    print '2013-12-25'
class balloon(object):
    unique_colors=set()
    def __init__(self,color):
        self.color=color
        balloon.unique_colors.add(color)

    @staticmethod
    def uniqueColorCount():
        return len(balloon.unique_colors)

    @staticmethod
    def uniqueColors():
        return balloon.unique_colors.copy()

装饰器

猜你喜欢

转载自blog.csdn.net/rosefun96/article/details/79439809