如何获取 Python 中类的文件路径?

给定 Python 中的类 C,如何确定在哪个文件中定义了该类?我需要的东西,可以工作从类 C,或从一个实例关闭 C。

The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.

Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".

62575 次浏览

尝试:

import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)

您可以使用 视察模块,如下所示:

import inspect
inspect.getfile(C.__class__)

对于姜戈来说,这是错误的方法,而且非常强制。

典型的 Django 应用程序模式是:

      • Models.py
      • 视野,视野
      • /模板
        • Html
        • 等等。