How do I get the filepath for a class in Python?

冷暖自知 提交于 2019-11-27 00:32:25

问题


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".


回答1:


You can use the inspect module, like this:

import inspect
inspect.getfile(C.__class__)



回答2:


try:

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



回答3:


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.


来源:https://stackoverflow.com/questions/697320/how-do-i-get-the-filepath-for-a-class-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!