#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
#元描述符
#特点是: Using one or more methods of the host class to perform a task may be useful in reducing the amount of code required to use a class that provides steps, such as a chain descriptor that invokes a system method of a class to return a set of results that can be stopped at the time of failure. and equipped with a callback mechanism to gain more control over the process, as follows
Class Chainer (object):
def __init__ (Self,a,b=notimplementederror):
Self._a=a
Self._b=b
def __get__ (self, instance, owner):
If instance is None:
#只针对实例
return self
Result=[]
For Methond in Self._a:
Result.append (Methond (instance))
If Self._b is not None:
If not Self._b (Instance,methond,result):
Break
return result
#这一实现各种类方法之上运行计算能与记录器这样的外部元素结合起来, as follows
Class Textprocess (object):
def __init__ (Self,text):
Self.text=text
def normalize (self):
If Isinstance (self.text,list):
Self.text=[t.lower () for T in Self.text]
Else
Self.text=self.text.lower ()
def split (self):
If not isinstance (self.text,list):
Self.text=self.text.split ()
def treshold (self):
If not isinstance (self.text,list):
If Len (self.text) <2:
Self.text= "
Self.text=[w for W in Self.text If Len (w) >2]
def logger (insetace,method,results):
print ' calling%s '%method.__name__
Return True
def add_sequen_ce (name,sequence):
SetAttr (Textprocess,name,chainer ([GetAttr (Textprocess,n) for n in Sequence],logger))
#add_sequen_ce用来动态的定义一个新链式调用方法的描述符, the result of this combination can be saved in the class definition, as follows
Add_sequen_ce (' Simoke_clean ', (' Split ', ' Trshold '))
My=textprocess (' My Taylor is Rich ')
My.simple_chean
My.text
#执行另一个序列
Add_sequen_ce (' Simoke_clean ', (' Normailze ', ' Split ', ' Trshold '))
My.simple_chean
My.text
#由于python动态特性, you can add this descriptor at run time to perform meta-programming
#定义
"""
Meta-programming (meta-programming) is a technique for adding new computing functions at run time or changing the behavior of an existing function, unlike programming, in other languages where new blocks of code need to be created rather than providing a simple block of code that can handle the most
It is also different from {Generative Programming {generative Programming}}, which programmatically generates a static source code through a module, which can be seen in the following way: En.wikipedia.org/wiki/generative programming
"""
Python advanced Programming descriptor and properties