2010-01-19 154 views
4
獲得派生類的模塊文件路徑

假設你有以下幾點:通過繼承

$ more a.py 
import os 

class A(object): 
    def getfile(self): 
     return os.path.abspath(__file__) 

-

$ more b.py 
import a 

class B(a.A): 
    pass 

-

>>> import b 
>>> x=b.B() 
>>> x.getfile() 
'/Users/sbo/tmp/file/a.py' 

這是顯而易見的。這段代碼沒有意外。但是假設我想x.getfile()返回b.py的路徑,而不必B類下定義GETFILE()的另一個副本

我沒有這個

import os 
import inspect 

class A(object): 
    def getfile(self): 
     return os.path.abspath(inspect.getfile(self.__class__)) 

我在想,如果還有另外一種策略(無論如何,我想寫在這裏,以便對其他人有用)或者我提出的解決方案的潛在問題。

CW,因爲它更是一個討論的問題,或者是/否樣的問題

回答

8
sys.modules[self.__class__.__module__].__file__ 
+0

我喜歡這一點,但有一點要注意的是,你會得到字節編譯模塊。 – snarkyname77 2010-01-19 12:57:03

+1

我不知道。我認爲這很糟糕。這是一個糟糕的方法,任何使用它的人都是壞人。 – 2010-01-19 12:58:38

+0

和頭kit小貓? :d – 2010-01-20 02:17:56

1

之所以能夠在Python 3得到這個工作如下:

import os 

class Parent: 

    def __init__(self, filename=__file__): 
     self.filename = filename 

    def current_path(self): 
     pth, _ = os.path.split(os.path.abspath(self.filename)) 
     return pth 

然後在不同的模塊...

from practice.inheritance.parent import Parent 

class Child(Parent): 

    def __init__(self): 
     super().__init__(__file__) 

...從任Parent或訪問按預期返回相應的模塊路徑。

>>> from practice.inheritance.parent import Parent 
>>> parent = Parent() 
>>> print(parent.current_path()) 
/Users/davidevans/PycharmProjects/play35/practice/inheritance 

>>> from practice.inheritance.subpackage.child import Child 
>>> child = Child() 
>>> print(child.current_path()) 
/Users/davidevans/PycharmProjects/play35/practice/inheritance/subpackage