【问题标题】:How to get the name of the file containing the class? [duplicate]如何获取包含该类的文件的名称? [复制]
【发布时间】:2017-06-08 16:21:56
【问题描述】:

是否可以获取包含该类的文件的名称?变量exporter是下面的一个类。

def main(exporter):

    v = exporter
    print v # <__main__.Vudu object at 0x106ea5210>
            # The class is "Vudu" and the filename that contains that class
            # is called vudu_exporter. How would I get "vudu_exporter" ?

更新:以下方法用于获取包含该类的脚本的名称:

script_name = os.path.basename(inspect.getfile(v.__class__))

【问题讨论】:

  • vudo.vudu_exporter.__file__ 应该包含它的名字。
  • 什么课?您还没有向我们展示任何课程。

标签: python


【解决方案1】:

在类/函数/方法/模块上调用inspect.getfile。它不能保证有效,但它比仅检查对象的 the __file__ attribute 更可靠(例如,在 Python 3.5 上,inspect.getfile(collections.defaultdict) 有效,而 collections.defaultdict.__file__ 引发 AttributeError)。

如果你有一个实例,如果不先转换为类,这将不起作用,例如inspect.getfile(type(instance))(在 Python 2 上,instance.__class__ 使用旧式类可能更可靠);它只能告诉你类是在哪里定义的,而不是实例是在哪里定义的。

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2011-12-22
    • 2014-02-23
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多