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())

Python 实践--混入类的更多相关文章

  1. Python编程从入门到实践笔记——类

    Python编程从入门到实践笔记——类 #coding=gbk #Python编程从入门到实践笔记——类 #9.1创建和使用类 #1.创建Dog类 class Dog():#类名首字母大写 " ...

  2. python 混入类MixIn

    写在前面 能把一件事情说的那么清楚明白,感谢廖雪峰的官方网站. 1.为什么要用混入类?(小白入门) 继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能. step1: 回忆一下 ...

  3. Python实践之(七)逻辑回归(Logistic Regression)

    机器学习算法与Python实践之(七)逻辑回归(Logistic Regression) zouxy09@qq.com http://blog.csdn.net/zouxy09 机器学习算法与Pyth ...

  4. 机器学习算法与Python实践之(四)支持向量机(SVM)实现

    机器学习算法与Python实践之(四)支持向量机(SVM)实现 机器学习算法与Python实践之(四)支持向量机(SVM)实现 zouxy09@qq.com http://blog.csdn.net/ ...

  5. 机器学习算法与Python实践之(三)支持向量机(SVM)进阶

    机器学习算法与Python实践之(三)支持向量机(SVM)进阶 机器学习算法与Python实践之(三)支持向量机(SVM)进阶 zouxy09@qq.com http://blog.csdn.net/ ...

  6. 机器学习算法与Python实践之(二)支持向量机(SVM)初级

    机器学习算法与Python实践之(二)支持向量机(SVM)初级 机器学习算法与Python实践之(二)支持向量机(SVM)初级 zouxy09@qq.com http://blog.csdn.net/ ...

  7. 机器学习算法与Python实践之(五)k均值聚类(k-means)

    机器学习算法与Python实践这个系列主要是参考<机器学习实战>这本书.因为自己想学习Python,然后也想对一些机器学习算法加深下了解,所以就想通过Python来实现几个比较常用的机器学 ...

  8. (转) K-Means聚类的Python实践

    本文转自: http://python.jobbole.com/87343/ K-Means聚类的Python实践 2017/02/11 · 实践项目 · K-means, 机器学习 分享到:1 原文 ...

  9. 机器学习算法与Python实践之(六)二分k均值聚类

    http://blog.csdn.net/zouxy09/article/details/17590137 机器学习算法与Python实践之(六)二分k均值聚类 zouxy09@qq.com http ...

随机推荐

  1. java源码 -- AbstractCollection抽象类

    简介  AbstractCollection是一个抽象类,它实现了Collection中除了iterator()和size()之外的所有方法.AbstractCollection的主要作用是方便其他类 ...

  2. Feign【首次请求失败】

    当feign和ribbon整合hystrix之后,可能会出现首次调用失败的问题,出现原因分析如下: hystrix默认的超时时间是1秒,如果接口请求响应超过这个时间,将会执行fallback,spri ...

  3. 抽象类 and 接口

    目录 抽象类 抽象类的域和方法的权限: 接口 接口中的域和方法的权限: 实现多个接口 接口继承 接口嵌套 抽象类 一个类,如果有抽象方法(没有方法体),则该类必须被限定为抽象类(abstract):当 ...

  4. 矩阵拿宝物--Codeforces 1201D - Treasure Hunting Codeforces Round #577 (Div. 2)

    网上题解比较少,自己比较弱研究了半天(已经过了),希望对找题解的人有帮助 题目链接:https://codeforc.es/contest/1201/problem/D 题意: 给你一个矩形,起始点在 ...

  5. golang字符串常用的系统函数

    1.统计字符串的长度,按字节len(str) str := "hello北京" fmt.Println("str len=", len(str)) 2.字符串遍 ...

  6. Python开发【第五章】:常用模块

    一.模块介绍: 1.模块定义 用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质上就是.py结尾python文件 分类:内置模块.开源模块.自定义模块 2.导入模块 本质:导 ...

  7. 数据结构——java实现栈

    栈 定义: 栈是一种先进后出的数据结构,我们把允许插入和删除的一端称为栈顶,另一端称为栈底,不含任何元素的栈称为空栈 栈的java代码实现: 基于数组: import org.junit.jupite ...

  8. Zuma CodeForces - 607B (区间DP)

    大意: 给定字符串, 每次删除一个回文子串, 求最少多少次删完. #include <iostream> #include <cstdio> #define REP(i,a,n ...

  9. (九)easyUI之选项卡

    前台 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncodi ...

  10. jvm的内存区域介绍

    什么是jvm? JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的 ...