代码之家  ›  专栏  ›  技术社区  ›  Alec

是否有函数返回在其中定义了用户定义类的文件?

  •  1
  • Alec  · 技术社区  · 5 年前

    我试着用 inspect.getfile() ,但没用

    from inspect import getfile
    
    class A: pass
    
    getfile(A.__class__)
    

    结果

    Traceback (most recent call last):
      File "classtest.py", line 5, in <module>
        getfile(A.__class__)
      File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/inspect.py", line 653, in getfile
        raise TypeError('{!r} is a built-in class'.format(object))
    TypeError: <module 'builtins' (built-in)> is a built-in class
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   Philip Tzou    5 年前

    A 已经是一个类了。 A.__class__ 在Python 3中返回它的元类 type 'builtins' 模块。

    将此文件另存为.py文件并使用Python运行:

    from inspect import getfile
    
    class A: pass
    
    print(getfile(A))
    

    如果在Python终端中复制并粘贴上面的代码,您将收到类似的错误。因为在终点站 class A 在模块中定义 '__main__' ,它也被视为Python中的内置模块。

        2
  •  0
  •   dr jimbob    5 年前

    将以下代码保存到当前目录中的文件中( /home/jimbob/test/ 在本例中)调用 example.py

    class MyExample:
        pass
    

    然后转到python解释程序:

    In [1]: from example import MyExample
    
    In [2]: import inspect
    
    In [3]: inspect.getfile(MyExample)
    Out[3]: '/home/jimbob/test/example.py'