2010-01-19 88 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