Mix-in:混入类是一种Python程序设计中的技术,作用是在运行期间动态改变类的基类或类的方法,从而使得类的表现可以发生变化。可以用在一个通用类接口中。
在实践一个 解析XML文件的实践中,体会动态改变的格式。
格式一般是:
定义一个基类:
class base:
def startElement(self,prefix,name,*args):
self.callback('Start',name,*args)
def callback(self,prefx,name,*args):
mname = prefix + name
method = getattr(self,mname,None)
if callbale(method): method(*args)
然后定义一个子类,在里面实现prefix+name的方法。
处理xml的内置库:
from xml.sax.hander import ContentHandler
from xml.sax import parse
parse('xmlfile', instanceofContentHandler)
from os import path from xml.sax.handler import ContentHandler from xml.sax import parse
__metaclass__ = type
class Dispatcher: def __init__(self): pass def startElement(self,name,attrs): self.dispatch('start',name,attrs) def endElement(self,name): self.dispatch('end',name)
def dispatch(self,prefix,name,attrs=None): propName = prefix + name.capitalize() dname = 'default' + prefix.capitalize() method = getattr(self,propName,None) if callable(method): if prefix == 'start': method(attrs) else: method() else: method = getattr(self,dname,None) if callable(method): if prefix == 'start': method(name,attrs) else: method(name)
class Sub_Dispatcher(Dispatcher,ContentHandler): in_dir = False in_page = False outer = None files = [] def characters(self,content): print content if self.in_page: self.outer.write(content) def startPage(self,attrs): self.in_page = True fname = attrs['name'] + '.html' self.outer = open(fname,'w') if self.in_dir: self.files.append(fname) document =''' <html> <head> <title>%s</title> </head> <body> ''' self.outer.write(document % attrs['title']) def endPage(self): document = '</body></html>' self.outer.write(document) self.outer.close() self.in_page = False def startDirectory(self,attrs): self.in_dir = True self.fullpath = path.join(path.curdir,attrs['name']) if not path.exists(self.fullpath): from os import mkdir mkdir(self.fullpath) def endDirectory(self): from distutils.file_util import move_file for f in self.files: move_file(f,path.join(self.fullpath,f)) def defaultStart(self,name,attrs): self.outer.write('<' + name + ' ') for key,value in attrs.items(): self.outer.write('%s="%s" '%(key,value)) self.outer.write('>') def defaultEnd(self,name): self.outer.write('</' + name + '>') def startWebsite(self,attrs): pass def endWebsite(self): pass parse('website.xml',Sub_Dispatcher())
|