34
  • 运行代码的文件名
  • 运行代码的类的名称
  • 运行代码的方法的名称(类的属性)
4

4 回答 4

33

以下是每个示例:

from inspect import stack

class Foo:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print stack()[0][3]

f = Foo()
于 2009-05-21T17:34:00.637 回答
11
import sys

class A:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print sys._getframe().f_code.co_name

a = A()
于 2009-05-21T17:34:10.277 回答
5
self.__class__.__name__  # name of class i'm in

其余的 sys 和 trace 模块

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/writings/diary/archive/2005/04/20/ tracking_python_code.html

您是否希望它用于错误报告,因为回溯模块可以处理:

http://docs.python.org/library/traceback.html

于 2009-05-21T17:28:33.487 回答
3

非常小心。考虑:

class A:
    pass

B = A
b = B()

这里的“类名”是b什么?是A还是B?为什么?

关键是,您不需要知道或关心。一个对象就是它:它的名字很少有用。

于 2009-05-21T21:39:35.370 回答