假设您有以下内容:
$ 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/