python的装饰器和@property

参考:http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html

 

这个是没有参数的形式,这个也没有返回值

import time
 
def timeit(func):
    def wrapper():
        start = time.clock()
        func()
        end =time.clock()
        print 'used:', end - start
    return wrapper
 
@timeit
def foo():
    print 'in foo()'
 
foo()

对固定参数的函数进行修饰

# -*- coding:gbk -*-
'''示例5: 对带参数的函数进行装饰,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''
 
def deco(func):
    def _deco(a, b):
        print("before myfunc() called.")
        ret = func(a, b)
        print("  after myfunc() called. result: %s" % ret)
        return ret
    return _deco
 
@deco
def myfunc(a, b):
    print(" myfunc(%s,%s) called." % (a, b))
    return a + b
 
myfunc(1, 2)
myfunc(3, 4)

参数数量不确定

# -*- coding:gbk -*-
'''示例6: 对参数数量不确定的函数进行装饰,
参数用(*args, **kwargs),自动适应变参和命名参数'''
 
def deco(func):
    def _deco(*args, **kwargs):
        print("before %s called." % func.__name__)
        ret = func(*args, **kwargs)
        print("  after %s called. result: %s" % (func.__name__, ret))
        return ret
    return _deco
 
@deco
def myfunc(a, b):
    print(" myfunc(%s,%s) called." % (a, b))
    return a+b
 
@deco
def myfunc2(a, b, c):
    print(" myfunc2(%s,%s,%s) called." % (a, b, c))
    return a+b+c
 
myfunc(1, 2)
myfunc(3, 4)
myfunc2(1, 2, 3)
myfunc2(3, 4, 5)

 

 

@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式

比如

#coding=utf-8

class person(object):

    def __init__(self, name, age):
        self._age = age
        self._name = name

    def get_name(self):
        return self._name

    @property
    def get_age(self):
        return self._age

p = person("hehe", 20)
print p.get_name()
print p.get_age

 

posted @ 2014-04-07 20:55  virusdefender  阅读(348)  评论(0编辑  收藏  举报