简体   繁体   中英

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

In Python, is it possible to print the "class and function name" whenever the "Print" function is called?

For excample,

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

c = SimpleClass()
c.function1()

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

Use logging module instead of print statements.

The list of available attributes are located here , including: args, asctime, created, exc_info, filename, funcName, levelname, levelno, lineno, module, msecs, message, msg, name, pathname, process, processName, relativeCreated, thread, threadName .

You're using Python 2.x it looks like, so print is not a function and can't be overridden like you want. You could, however, make print a function as it is in Python 3.x using from __future__ import print_function assuming you're using Python 2.6 or later. Then you could pretty trivially override it with your own print that does as you like. (Well, the overriding is trivial; getting the class and method name is a little less so.)

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)

Digging self out of the function's local variables to see if it's a method is kind of a cheat, since that's only a convention and self could refer to any value, but it should work 99.44% of the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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