程式扎記: [ Python 常見問題 ] How do I get the filepath for a class in Python?

標籤

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'


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!