【问题标题】:How to write an If else condition to choose between two functions如何编写 If else 条件以在两个函数之间进行选择
【发布时间】:2023-03-05 22:09:01
【问题描述】:

场景: 我有一个文件 project.py,其工作是导航到另一个文件夹以获取存储在 .yml 文件中的环境变量。这里有两种情况,一种是导航到一个目录,另一种是导航到我使用 zipfile 模块的 egg 文件中的目录。如何在 project.py 中包含这两种情况并编写一个 if else 条件以根据目录类型在这两个函数之间进行选择。下面是代码。我是编程新手,非常感谢任何帮助。

项目.py

类项目(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

如何写一个条件来在上述两个函数之间进行选择。

【问题讨论】:

  • 你写一个__init__(self, .....),然后在里面检查你要做什么。如果您遵循 oop,您可能想要构建一个抽象类并派生两个子类,如果您的类也做其他事情。或者只是将路径/文件的名称提供给函数,如果它是 ZIP,则执行 this else do that
  • 你在这里复制了很多代码。我没有通读所有内容,但我只看到了实际上不同的一两行。也许你只需要一个 __init__ 中的 if 语句
  • @user1558604 是的,实际上是在考虑这个问题,关于如何在单个 init 中执行此操作的任何建议?
  • @PatrickArtner 我刚刚尝试实现它,虽然它不是我要导航到的 zip,但它仍然采用 zipfile 大小写,因为它位于 #__init__ 函数的开头。跨度>
  • 从您发布的代码中不清楚问题出在哪里。简化它:创建一个接受文件路径的类并决定路径s extension what part of your single __init__` 应该被执行。简化问题有助于调试它们 - 并让minimal reproducible example 更好地向我们展示您的问题

标签: python if-statement zipfile egg


【解决方案1】:

如果两个__init__s 都属于同一个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

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2012-10-11
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多