[英]How do I get the current file, current class, and current method with Python?
以下是每個例子:
from inspect import stack
class Foo:
def __init__(self):
print __file__
print self.__class__.__name__
print stack()[0][3]
f = Foo()
import sys
class A:
def __init__(self):
print __file__
print self.__class__.__name__
print sys._getframe().f_code.co_name
a = A()
self.__class__.__name__ # name of class i'm in
其余的sys和跟蹤模塊
http://docs.python.org/library/sys.html http://docs.python.org/library/trace.html
更多信息: https : //mail.python.org/pipermail/python-list/2001-August/096499.html和http://www.dalkescientific.com/writingings/diary/archive/2005/04/20/ tracing_python_code.html
你想要它用於錯誤報告嗎,因為回溯模塊可以處理:
要非常小心。 考慮:
class A:
pass
B = A
b = B()
這里b
的“班級名稱”是什么? 是A還是B? 為什么?
關鍵是,你不應該知道或關心。 對象就是這樣的:它的名字很少有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.