2016年12月9日 星期五

[ Python 常見問題 ] How do I get the filepath for a class in Python?

Source From Here
Question
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.

How-To
You can use the inspect module, like this:
- A.py
  1. class A(object):  
  2.     def __init__(self):  
  3.         print "Class A constructor"  
- B.py
  1. class B(object):  
  2.     def __init__(self):  
  3.         print "Class B constructor"  
Then enter Python Interactive Mode:
>>> from A import *
>>> a = A()
Class A constructor
>>> from B import *
>>> b = B()
Class B constructor
>>> import inspect
>>> inspect.getfile(a.__class__)
'A.py'
>>> inspect.getfile(b.__class__)
'B.py'
>>> inspect.getfile(A)
'A.py'
>>> inspect.getfile(B)
'B.py'


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...