问题:如何在Python中获取类的文件路径?

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

之所以这样做,是因为我通常不喜欢将属于同一文件的文件放在同一文件夹中。我想创建一个使用Django模板将其自身呈现为HTML的类。基本实现应根据定义类的文件名来推断模板的文件名。

假设我在文件“ base / artifacts.py”中放置了一个LocationArtifact类,那么我希望默认行为是模板名称为“ base / LocationArtifact.html”。

Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off 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”.


回答 0

您可以使用检查模块,如下所示:

import inspect
inspect.getfile(C.__class__)

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)

回答 1

尝试:

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

try:

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

回答 2

对于Django而言,这是错误的方法,并且实际上是强迫的。

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

  • /项目
    • / appname
      • models.py
      • views.py
      • /模板
        • index.html
        • 等等

This is the wrong approach for Django and really forcing things.

The typical Django app pattern is:

  • /project
    • /appname
      • models.py
      • views.py
      • /templates
        • index.html
        • etc.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。