通过继承获取派生类的模块文件路径

时间:2010-01-19 10:30:57

标签: python

假设您有以下内容:

$ 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因为它更像是一个讨论问题,或者是/否是一个问题

2 个答案:

答案 0 :(得分:10)

sys.modules[self.__class__.__module__].__file__

答案 1 :(得分:2)

能够在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__)

...从current_path()Parent访问Child会按预期返回相应的模块路径。

>>> 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