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静态方法类方法

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


原文地址:https://www.cnblogs.com/yxwkf/p/3907621.html