繁体   English   中英

每当我在python中打印某些内容时,是否有一种方法可以打印类/函数名称?

[英]Is there a way to print the class / function name everytime i print something in python?

在Python中,每当调用“打印”函数时,是否可以打印“类和函数名”?

例如,

class SimpleClass:
    def function1(self):
        print "This is the printed msg"

c = SimpleClass()
c.function1()

"Output wanted" 
SimpleClass:function1 - "This is the printed msg"

使用日志记录模块而不是打印语句。

可用属性的列表位于此处 ,包括: args, asctime, created, exc_info, filename, funcName, levelname, levelno, lineno, module, msecs, message, msg, name, pathname, process, processName, relativeCreated, thread, threadName

您正在使用Python 2.x,看起来像这样,所以print不是函数,不能随意覆盖它。 但是, 可以使用from __future__ import print_function 使 print成为Python 3.x中的函数, from __future__ import print_function您使用的是Python 2.6或更高版本。 然后,您可以用自己喜欢的print轻松地覆盖它。 (好吧,重载是微不足道的;获得类和方法的名称要少得多。)

from inspect import currentframe

_print = print

def print(*args, **kwargs):
    frame = currentframe().f_back
    fname = frame.f_code.co_name
    self  = frame.f_locals.get("self", None)
    qname = (type(self).__name__ + "." + fname) if self else fname
    _print(qname, end=": ")
    _print(*args, **kwargs)

从函数的局部变量中挖出self以查看它是否是一种方法,这是一种作弊,因为这只是一个约定, self可以引用任何值,但是它应该在99.44%的时间内工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM