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

前端 未结 3 1802
执笔经年
执笔经年 2020-12-07 23:44

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.

<
相关标签:
3条回答
  • 2020-12-08 00:17

    You can use the inspect module, like this:

    import inspect
    inspect.getfile(C.__class__)
    
    0 讨论(0)
  • 2020-12-08 00:18

    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.
    0 讨论(0)
  • 2020-12-08 00:28

    try:

    import sys, os
    os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)
    
    0 讨论(0)
提交回复
热议问题