zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    (转载)C++ string中find() ,rfind() 等函数 用法总结及示例
    UVA 230 Borrowers (STL 行读入的处理 重载小于号)
    UVA 12100 打印队列(STL deque)
    uva 12096 The SetStack Computer(STL set的各种库函数 交集 并集 插入迭代器)
    uva 1592 Database (STL)
    HDU 1087 Super Jumping! Jumping! Jumping!
    hdu 1176 免费馅饼
    HDU 1003 Max Sum
    转战HDU
    hust 1227 Join Together
  • 原文地址:https://www.cnblogs.com/virusdefender/p/3650675.html
Copyright © 2011-2022 走看看