场景: 我有一个文件project.py,其工作是导航到另一个文件夹以获取存储在.yml文件中的环境变量。这里有两种情况,一种工作是导航到我使用zipfile模块的egg文件中的目录,另一种是导航到egg文件中的目录。如何将这两种情况都包含在project.py中,并编写一个if else条件以根据目录类型在这两个函数之间进行选择。下面是代码。我是编程的新手,将不胜感激。
Class Proj(dict):
def __init__(self, envmt, app_path):
self.config_dict = {}
self.envmt = envmt
with zipfile.Zipfile("C:/Users/project/poc/dist/project-1.0.0-py3.6", 'r') as myzip:
config = load(myzip.open("base.yml_path"))
for key, value in config.items():
configvals = value
for key in configvals:
self.config_dict[key]= configvals[key]
self.base = config
with zipfile.Zipfile("C:/Users/project/poc/dist/project-1.0.0-py3.6", 'r') as myzip:
config = load(myzip.open("env.yml_path"))
for key, value in config.items():
configvals = value
for key in configvals:
self.config_dict[key]= configvals[key]
self.env = config
def __init__(self, envmt, app_path):
self.config_dict = {}
self.envmt = envmt
with open(os.path.join(app_path, 'config', 'base.yml'), 'r') as cfile:
config = load(cfile)
for key, value in config.items():
configvals = value
for key in configvals:
self.config_dict[key]= configvals[key]
self.base = config
with open(os.path.join(app_path, 'config', envmt+'.yml'), 'r') as cfile:
config = load(cfile)
for key, value in config.items():
configvals = value
for key in configvals:
self.config_dict[key]= configvals[key]
self.env = config
如何编写一个条件以在上述两个函数之间进行选择。
答案 0 :(得分:0)
如果两个__init__
属于同一个class
,则仅使用最后一个,请考虑编写这样的类:
class AClass:
def __init__(self, envmt, app_path):
if condicion == True:
self._init_a(envmt, app_path)
else:
self._init_b(envmt, app_path)
def _init_a(self, envmt, app_path):
# run code here
def _init_b(self, envmt, app_path):
# run code here