在调用工厂方法之前实例化超类

问题描述 投票:0回答:1

我正在尝试在调用子类之前初始化超类。这是我正在尝试做的一个例子:

class AbstractSourceParser(object):

    def __init__(self, filepath):

        self.source_type = get_type_from_filepath(filepath)

    @staticmethod
    def factory(source_type):

        source_type = source_type.upper() if source_type else None

        if source_type == SourceType.CSV.upper():
            return CSVSourceParser() 

class CSVSourceParser(AbstractSourceParser):
    ...

然后我希望能够像这样调用它:

parser = AbstractSourceParser("/tmp/file.csv").factory(self.type)

我认为我上面写的内容在代码中没有意义,但基本上我想在将一些数据传递给超类之后检索工厂方法。怎么做?

目前,我正在做的是以下,我认为这是非常丑陋的(如果不是可能不正确) -

>>> _parser = AbstractSourceParser("/tmp/file.csv")
>>> parser = _parser.factory(_parser.source_type) 
python python-3.x multiple-inheritance
1个回答
0
投票

您可以使factory()成为常规实例方法,并让它完成工作:

class AbstractSourceParser(object):
    def __init__(self, filepath):
        self.source_type = get_type_from_filepath(filepath)

    def factory(self, source_type=None):
        if source_type is None:
            source_type = self.source_type

        source_type = source_type.upper() if source_type else None

        if source_type == SourceType.CSV.upper():
            return CSVSourceParser()

因此,如果您想要在父构造函数中定义的源类型,则可以调用不带参数的factory()。但如果你愿意,你仍然可以提供不同的source_type

这会得到你所要求的吗?

© www.soinside.com 2019 - 2024. All rights reserved.