Python 学习笔记9(装饰器,decorator)
2016-05-10 13:49
585 查看
31 装饰器
装饰器可以对一个函数、方法或者类进行加工,是一种高级的python语法。装饰函数
接收一个可调用对象作为输入参数,并返回一个新的可调用对象.把函数传递给装饰器,然后增加新的功能,返回一个新的函数重赋值给原函数
语法:
def decorator1... # 定义装饰器
@decorator1 # 定义函数前,@装饰器
def function1 # 定义要加工的函数
例子:
def mydecorator(myfunction): def new_myfunction(a,b): print("modify myfunction:") # 1 return myfunction(a,b) return new_myfunction @mydecorator def myfunction(x,y): print("old myfunction") #2 return x*y print(myfunction(6,7))
顺序: 先执行装饰器里面的语句1,再执行原函数的语句2。
含参的装饰器
在上面的例子中,@mydecorator默认后面的函数是它的唯一参数;实际上,装饰器也可以含有其它参数,如@mydecorator(a)
装饰类
一个装饰器可以接收一个类,并返回一个类,从而起到加工类的效果。例子:
def mydecorator(myclass): class newClass: def __init__(self,age): self.display_time=0 self.wrapped=myclass(age) #把原类赋值给新类 def display(self): self.display_time+=1 print("this is ",self.display_time,"th display time") #1 self.wrapped.display() # 调用原类的函数 return newClass @mydecorator class Bird: def __init__(self,age): self.age=age def display(self): print("My age is ", self.age) #2 eagleLord=Bird(5) for i in range(4): eagleLord.display()
顺序与装饰函数类似。先装饰类1,后原类2。
相关文章推荐
- [LeetCode]题解(python):144-Binary Tree Preorder Traversal
- python 获取局域网内的广播地址
- python 建立ssh连接 并登陆mysql
- Python学习笔记:字典(dict)有关内容
- python的优点
- ubuntu12.04安装python3.5及pip3和setuptools
- python文件读写操作
- python main函数中变量默认为global variable & SIGKILL SIGSTOP 无法捕获
- Python Built-in Funcitons
- 人人影视自动签到Python脚本
- python+opencv实现霍夫变换检测直线
- 文件拷贝
- python中关键词with的使用
- Python string reverse
- python socket 检测服务器端口
- python使用嵌套序列
- python daemon 守护进程对信号的处理
- Python 自定义信号处理
- Python的信号处理与程序退出
- 百度网盘爬虫Python