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

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

最佳答案

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

关于python - 通过继承获取派生类的模块文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092752/

相关文章:

python - Facebook Canvas 应用程序 - 循环登录重定向

python - 如何将包含日期的 csv 数据加载到 numpy 数组中?

python - Python 的 IDLE 与其命令行之间的区别

python - 在 pandas 的数据框中用 NaN 替换所有值

python - Flask:忽略 'category' 参数的 Flash 函数

python - App Engine NDB 事务冲突

python - Plotly:如何使用 Pandas 数据框作为源按行填充表

python - 在 Python 中将复杂的键(元组)存储到 JSON 中

jquery - 目前(2011 年)通过跨域 AJAX 的 REST 是个坏主意吗?

python - 正则表达式替换python中的文本