如何使用 Python 获取当前文件、当前类和当前方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/894088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the current file, current class, and current method with Python?
提问by Max Frai
- Name of the file from where code is running
- Name of the class from where code is running
- Name of the method (attribute of the class) where code is running
- 运行代码的文件名
- 运行代码的类的名称
- 运行代码的方法的名称(类的属性)
采纳答案by Andrew Hare
Here is an example of each:
以下是每个示例:
from inspect import stack
class Foo:
def __init__(self):
print __file__
print self.__class__.__name__
print stack()[0][3]
f = Foo()
回答by mtasic85
import sys
class A:
def __init__(self):
print __file__
print self.__class__.__name__
print sys._getframe().f_code.co_name
a = A()
回答by SpliFF
self.__class__.__name__ # name of class i'm in
for the rest the sys and trace modules
其余的 sys 和 trace 模块
http://docs.python.org/library/sys.htmlhttp://docs.python.org/library/trace.html
http://docs.python.org/library/sys.html http://docs.python.org/library/trace.html
Some more info: https://mail.python.org/pipermail/python-list/2001-August/096499.htmland http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html
更多信息:https: //mail.python.org/pipermail/python-list/2001-August/096499.html和 http://www.dalkescientific.com/writings/diary/archive/2005/04/20/ trace_python_code.html
did you want it for error reporting because the traceback module can handle that:
您是否希望它用于错误报告,因为回溯模块可以处理:
回答by Daniel Roseman
Be verycareful. Consider:
要非常小心。考虑:
class A:
pass
B = A
b = B()
What is the 'class name' of b
here? Is it A, or B? Why?
这里的“类名”是b
什么?是A,还是B?为什么?
The point is, you shouldn't need to know or care. An object is what it is: its name is very rarely useful.
关键是,你不需要知道或关心。一个对象就是它的样子:它的名字很少有用。