簡體   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