【问题标题】:Replace path in method of other class during runtime在运行时替换其他类方法中的路径
【发布时间】:2023-01-26 21:13:37
【问题描述】:

我在不同的模块中有两个类,一个类包含实际功能,另一个类包含测试功能。

ModuleA:
    def __init__(self, path):
        self.import_path = None

    def import_data(self):
        self.import_path = sales.__path__["data"]
        self.input = pd.read_excel(
            self.import_path,
            index_col=False,
            engine="openpyxl",
            dtype=object,
        )
        return self.input


ModuleB:
    def __init__(self, path):
        self.import_test_path = None

    def test_import_data(self):
        self.import_test_path = self.__path__["data"]

        # Replace actual data paths with test data paths
        ModuleA.import_path = self.import_test_path

        ModuleA.import_data()

问题是,虽然我在ModuleB中定义了一个测试路径,但我仍然无法覆盖在ModuleA中实例化的import_path,即使我调用该方法,因为路径是在方法中定义的。有没有办法用 ModuleA 的路径替换此路径,例如通过 Monkeypatching?谢谢!

【问题讨论】:

    标签: python oop testing pytest path-finding


    【解决方案1】:

    已找到答案。我只需要将硬编码路径放在 ModuleA 方法本身之外并放入其 init 方法中。然后,当只调用方法而不实例化类时,我可以传递正确的路径:

    ModuleA:
        def __init__(self, path):
            self.import_path = sales.__path__["data"]
    
        def import_data(self):
            self.input = pd.read_excel(
                self.import_path,
                index_col=False,
                engine="openpyxl",
                dtype=object,
            )
            return self.input
    

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 2018-01-03
      • 2014-07-06
      • 2018-01-06
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多