Python 导入触发函数的其他文件变量 returns 变量
Python import other file variable that triggers a function that returns variable
好的,问题是我需要导入一个变量,该变量需要触发一个函数来检查文件是否存在,如果不存在,下载文件并设置变量。我通常会从带有 getter 和 setter 的 class 获得此功能,但由于我不希望我的用户必须为 class 设置变量,这会带来一个有趣的问题。
所以这可行,但不具备所需的功能:
Run.py 文件:
from examples.mnist import images, labels, show
print(images)
print(labels)
show()
MNIST 文件:
images = "Images goes here"
labels = "Labels go here"
def show():
print("Im showing your image")
简单来说。如何在不让用户设置 object/class 的情况下导入具有 getter/setter 函数的变量?
您可以定义模块级别 __getattr__
,如 PEP 562 所指定:
# mnist.py
def __getattr__(name):
if name=='images':
if not file_exist_check():
download_file()
return read_file()
raise AttributeError(f"module {__name__} has no attribute {name}")
好的,问题是我需要导入一个变量,该变量需要触发一个函数来检查文件是否存在,如果不存在,下载文件并设置变量。我通常会从带有 getter 和 setter 的 class 获得此功能,但由于我不希望我的用户必须为 class 设置变量,这会带来一个有趣的问题。
所以这可行,但不具备所需的功能:
Run.py 文件:
from examples.mnist import images, labels, show
print(images)
print(labels)
show()
MNIST 文件:
images = "Images goes here"
labels = "Labels go here"
def show():
print("Im showing your image")
简单来说。如何在不让用户设置 object/class 的情况下导入具有 getter/setter 函数的变量?
您可以定义模块级别 __getattr__
,如 PEP 562 所指定:
# mnist.py
def __getattr__(name):
if name=='images':
if not file_exist_check():
download_file()
return read_file()
raise AttributeError(f"module {__name__} has no attribute {name}")