45 python printing overloading
我能够重载该print函数并从内部调用正常函数吗?我想要做的是在我要print调用的特定行之后print调用普通行print并将副本写入文件.
另外我不知道怎么超载print.我不知道如何做变长参数.我很快就会查看,但是 重载打印python告诉我,我不能print在2.x中超载,这就是我正在使用的.
Dev*_*yer 59
对于那些审查以前过时的答案的人,从版本发布的"Python 2.6"开始,对原始海报的问题有一个新的答案.
在Python 2.6及更高版本中,您可以禁用print语句以支持print函数,然后使用您自己的print函数覆盖print函数:
from __future__ import print_function
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments, other future statements, or blank lines before the __future__ line.
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
def print(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
__builtin__.print('My overridden print() function!')
return __builtin__.print(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
当然,您需要考虑此打印功能此时仅为模块范围.你可以选择覆盖__builtin__.print,但你需要保存原件__builtin__.print; 可能与__builtin__命名空间混淆.
小智 10
我遇到了同样的问题.
这个怎么样:
class writer :
def __init__(self, *writers) :
self.writers = writers
def write(self, text) :
for w in self.writers :
w.write(text)
import sys
saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There you go."
sys.stdout = saved
fout.close()
Run Code Online (Sandbox Code Playgroud)
它对我来说就像一个魅力.它取自http://mail.python.org/pipermail/python-list/2003-February/188788.html
Kva*_*ant 10
class MovieDesc:
name = "Name"
genders = "Genders"
country = "Country"
def __str__(self):
#Do whatever you want here
return "Name: {0}\tGenders: {1} Country: {2} ".format(self.name,self.genders,self.country)
)
Run Code Online (Sandbox Code Playgroud)
小智 6
举一个非常简单的例子,从 Python3.4 开始(尚未使用旧版本进行测试),这对我来说效果很好(放置在模块顶部):
import time
def dprint(string):
__builtins__.print("%f -- %s" % (time.time(), string))
print = dprint
Run Code Online (Sandbox Code Playgroud)
注意,这仅在字符串参数是字符串时才有效... YMMV
| 归档时间: |
|
| 查看次数: |
67266 次 |
| 最近记录: |