![](/img/trans.png)
[英]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.