[英]How to print a statement everytime when i call function inside class
[英]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"
您正在使用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.