【发布时间】:2018-01-10 09:01:18
【问题描述】:
假设我有一个接口类Base 打算被继承。我需要在Base 中定义一个静态方法,该方法将读取并打印一个文本文件旁边的后继定义。我的尝试如下。
示例结构:
.../module/
__init__.py
Base.py
A/
__init__.py
A.py
file.txt
B/
__init__.py
B.py
file.txt
Base.py:
import os.path
class Base:
@staticmethod
def print_file():
file = os.path.join(os.path.dirname(__file__), 'file.txt')
with open(file, 'r') as f:
print(f.read())
A.py(B.py 相同):
from module.Base import Base
class A(Base):
pass
当我导入A 类并调用A.print_file() 时,此代码尝试读取.../module/file.txt 而不是.../module/A/file.txt,因为__file__ 似乎是根据Base.py 而不是A.py 计算的。
有没有办法在静态方法中读取A/file.txt 和B/file.txt 而无需A.py 和B.py 中的附加代码?
【问题讨论】:
-
只是猜测:使用检查模块,例如:
inspect.getframeinfo(inspect.currentframe()).filename -
@jojo
print-在调用A.print_file()时,在静态方法的其余部分打印.../module/Base.py之前,正是这一行。似乎一切都是根据基类计算的。不过,谢谢,我会研究检查模块。 -
__file__将引用调用它的 当前 文件(模块)。
标签: python