#coding:utf-8
def output_xml(name):
print 'XML:%s' % name
def output_html(name):
print 'HTML:%s' % name
def output_doc(name):
print 'DOC:%s' % name
def putdoc(types,name):
print types,type(types)
print name,type(name)
eval('output_%s("%s")' % (types,str(name)))
putdoc('doc',"sam")
实例二:
有两个文件如下:
myoutformat.py #定义输出的文件格式
#coding:utf-8
class outputForm(object):
def output_html(self,data):
print 'html:',data
def output_xml(self,data):
print 'xml:',data
def output_text(self,data):
print 'text:',data
if __name__=="__main__":
pass
myout.py #调用输出文件格式模块,输出文件
#coding:utf-8
import myoutformat
def f(inst,form,data):
#inst.output_text 是默认的方法参数,返回函数(或者:getattr(inst,'output_text')),如果此处是个字符串,则返回该字符串。此处应该是函数名称,返回函数
fun=getattr(inst,"output_%s" % form,inst.output_text)
#调用函数fun
fun(data)
if __name__ == '__main__':
a=myoutformat.outputForm()
f(a,"html",'abc')
f(a,"xml",'abc')
f(a,"text",'abc')
f(a,"NAME",'abc')
结果:
html: abc
xml: abc
text: abc
text: abc