python的装饰器和@property
2014-04-07 20:55
363 查看
参考:http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
这个是没有参数的形式,这个也没有返回值
对固定参数的函数进行修饰
参数数量不确定
@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式
比如
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
相关文章推荐
- Python中的property() 函数 和@property 装饰符
- Python 装饰器,@property 以及 Pycaffe.py
- Python 装饰器,@property 以及 Pycaffe.py
- python内部装饰器@classmethod, @staticmethod, @property
- python面试常问的几个内置装饰器:@staticmethod、@classmethod和@property
- 理解Python中的装饰器(转载) -- 浅显易懂
- Python 装饰器简单介绍
- Python 学习入门(36)—— @property属性
- Python装饰函数
- 【Python】详解Python的装饰器
- Python 装饰器归纳总结
- Python基础知识:5:装饰器
- Python中实现装饰模式的三种方式
- 理解 python 装饰器
- python知识点3之装饰器及语法糖
- python的装饰器
- python中@property的用法
- python Class:面向对象高级编程 @property
- python 装饰器
- python Class:面向对象高级编程 @property