zoukankan      html  css  js  c++  java
  • python中的装饰器

        python中的装饰器能够装饰函数,也能够装饰类,功能是向函数或者类加入�一些功能。类似于设计模式中的装饰模式,它能够把装饰器的功能实现部分和装饰部分分开,避免类中或者函数中冗余的代码。

    装饰器装饰函数:

    def decrator(f1):
    	def newf():
    		print "strings will be connected:"
    		print f1();
    	return newf;
    	
    @decrator
    def strconnect():
    	x=raw_input("input the first string");
    	y=raw_input("input the second string");
    	return x+y;
    	
    strconnect();

        上面的代码,对函数strconnect加了装饰器,在装饰器decrator生成了新的函数newf,newf的函数体调用了f1函数,而且添加�了装饰功能。

    装饰器装饰类:

    def decrator(obj):
    	class newclass():
    		def __init__(self,s):
    			self.tmp=obj(s);
    		def show(self):
    			print "apple is good for your health";
    			print self.tmp.show();
    	return newclass;
    
    @decrator	
    class apple():
    	def __init__(self,s):
    		self.str=s;
    	def show(self):
    		return self.str;	
    t=apple('an apple a day keeps a doctor away');
    t.show();

        与装饰一个函数类似,装饰器也能够装饰类,装饰器decrator中产生了新的类newclass,newclass的构造方法多了一个參数s,用于生成被装饰的类的对象,self.tmp=obj(s)即实现了这个功能。装饰器中的show函数也是调用了被装饰的类的show函数,而且添加�了装饰代码。

        除了自己定义的装饰器,python还提供了自带的装饰器,如静态方法和类方法就是通过装饰器来实现的,有关静态方法和类方法的说明,在这里:python静态方法类方法

        装饰器装饰一个函数就可以返回一个新的函数,装饰一个类就可以返回一个新的类,扩展了原有函数或者类的功能。


  • 相关阅读:
    免费馅饼(HDU 1176 DP)
    搬寝室(HDU 1421 DP)
    FatMouse's Speed(HDU LIS)
    Bone Collector II(HDU 2639 DP)
    Palindrome(POJ 1159 DP)
    Proud Merchants(POJ 3466 01背包+排序)
    树的最大独立集
    Roads in the North(POJ 2631 DFS)
    Starship Troopers(HDU 1011 树形DP)
    Strategic game(POJ 1463 树形DP)
  • 原文地址:https://www.cnblogs.com/yxwkf/p/3907621.html
Copyright © 2011-2022 走看看