如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:04:24  来源:igfitidea点击:

How do I get the current file, current class, and current method with Python?

pythonfilenames

提问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 Daniel Roseman

Be verycareful. Consider:

非常小心。考虑:

class A:
    pass

B = A
b = B()

What is the 'class name' of bhere? 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.

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