假设您有以下内容:
$ more a.py
import os
class A(object):
def getfile(self):
return os.path.abspath(__file__)
Run Code Online (Sandbox Code Playgroud)
-
$ more b.py
import a
class B(a.A):
pass
Run Code Online (Sandbox Code Playgroud)
-
>>> import b
>>> x=b.B()
>>> x.getfile()
'/Users/sbo/tmp/file/a.py'
Run Code Online (Sandbox Code Playgroud)
这很清楚.这段代码并不奇怪.但是假设我希望x.getfile()返回b.py的路径,而不必在类B下定义另一个getfile()副本.
我这样做了
import os
import inspect
class A(object):
def getfile(self):
return os.path.abspath(inspect.getfile(self.__class__))
Run Code Online (Sandbox Code Playgroud)
我想知道是否有另一种策略(无论如何,我想在这里写它以便它对其他人有用)或者我提出的解决方案的潜在问题.
CW因为它更像是一个讨论问题,或者是/否是一个问题
Ign*_*ams 10
sys.modules[self.__class__.__module__].__file__
Run Code Online (Sandbox Code Playgroud)
能够在 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
Run Code Online (Sandbox Code Playgroud)
然后在不同的模块中......
from practice.inheritance.parent import Parent
class Child(Parent):
def __init__(self):
super().__init__(__file__)
Run Code Online (Sandbox Code Playgroud)
...访问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
Run Code Online (Sandbox Code Playgroud)