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

18 投票
2 回答
8737 浏览
提问于 2025-04-15 18:11

假设你有以下内容:

$ 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__))

我在想有没有其他的办法(无论如何,我想把它写在这里,以便对其他人有帮助),或者我提出的解决方案可能会有什么问题。

这更像是一个讨论性的问题,或者说是一个是/否的问题。

2 个回答

8

我在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__)

...从ParentChild中调用current_path(),都能如预期返回各自的模块路径。

>>> 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
18
sys.modules[self.__class__.__module__].__file__

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

撰写回答