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

发布于 2024-07-15 10:42:44 字数 324 浏览 5 评论 0原文

给定 Python 中的类 C,我如何确定该类是在哪个文件中定义的? 我需要一些可以从 C 类或 C 实例运行的东西。

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

假设我将一个类 LocationArtifact 放在文件“base/artifacts.py”中,那么我想要默认值行为是模板名称为“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 of C.

I am doing this because I am generally a fan of 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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笨死的猪 2024-07-22 10:42:44

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

import inspect
inspect.getfile(C.__class__)

You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)
潇烟暮雨 2024-07-22 10:42:44

尝试:

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

try:

import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)
再浓的妆也掩不了殇 2024-07-22 10:42:44

这对 Django 来说是错误的做法,而且确实是强迫性的。

典型的 Django 应用模式是:

  • /project
    • /应用程序名称
      • 模型.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.
恬淡成诗 2024-07-22 10:42:44

您可以使用错误来获取您的类的路径

import os
import traceback
class C:
  def getClassPath(self):
    #get foldet path
    try:
        raise ValueError("Example error")
    except Exception as e:
        tb = traceback.extract_tb(e.__traceback__)
       
        return os.path.dirname(tb[-1].filename)
c = C()
print('path is',c.getClassPath())

You can use the error to get the path of your class

import os
import traceback
class C:
  def getClassPath(self):
    #get foldet path
    try:
        raise ValueError("Example error")
    except Exception as e:
        tb = traceback.extract_tb(e.__traceback__)
       
        return os.path.dirname(tb[-1].filename)
c = C()
print('path is',c.getClassPath())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文