您的位置:首页 > 编程语言 > Python开发

【冷知识】在python2.7或更早的版本中模拟类似3.x的print函数

2015-12-31 13:18 483 查看
虽然这样做没有必要因为一般情况下,我们可以有更好的方式去实现:

例如使用from __future__ import print_function来实现:

from __future__ import print_function
print(123,456,end='',file = (open('temp.txt','w'))
#它大致上等价于你在2.x内写 print >>open('temp.txt','w'),123,456,


但是以下实例能帮助更好的理解print内置函数的工作方式:

# -*- coding: utf-8 -*-

def print3(*args,**kargs):
'''
模拟print函数
在2.7或跟早的python版本中模拟一个能实现大部分3.x版本的print3函数
'''
import sys
sep = kargs.pop('sep',' ')   #字典的pop函数删除字典内指定键并返回值,如果没能找到键返回自己设置的值。
end = kargs.pop('end','\n')
file = kargs.pop('file',sys.stdout)   #打印流定向
if kargs: raise TypeError('extra keywords: %s'%kargs)  #抛出一个异常当函数被传入其他奇怪的参数时
output = ''
first = True
for arg in args:
output += ('' if first else sep) + str(arg)
first = False
file.write(output + end)  #写入文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python