可以为超类的构造函数返回子类的实例吗?

ACR*_*CRL 2 python oop

我正在解析二进制日志文件.日志文件的格式如下:每10个字节是一个记录,记录的第一个字节是记录类型,接下来的5个字节是时间戳,最后4个字节是记录类型特定的数据.

目前我正在做以下事情:

# read the input binary stream
with open(filename, mode='rb') as trace_stream:
    # create an empty list of trace records
    trace = []
    # iterate over each record in the binary stream
    for record_type, record_data in yield_record(trace_stream,
                                                 size=RECORD_LENGTH):
        # create a new record instance
        if record_type == SEN_RECORD:
            new_record = sen_record(record_data)
        elif record_type == DSP_RECORD:
            new_record = dsp_record(record_data)
        elif record_type == USO_RECORD:
            new_record = uso_record(record_data)
        elif record_type == SDM_RECORD:
            new_record = sdm_record(record_data)
        elif record_type == DOC_RECORD:
            new_record = doc_record(record_data)
        elif record_type == DAT_RECORD:
            new_record = dat_record(record_data)
        elif record_type == LAT_RECORD:
            new_record = lat_record(record_data)
        elif record_type == SWI_RECORD:
            new_record = swi_record(record_data)
        elif record_type == FTL_RECORD:
            new_record = ftl_record(record_data)

        # append this new record to our trace
        trace.append(new_record)
Run Code Online (Sandbox Code Playgroud)

其中sen_record,dsp_record,uso_record等都是通用记录类的子类

我想做的是以下内容:

# read the input binary stream
with open(filename, mode='rb') as trace_stream:
    # create an empty list of trace records
    trace = []
    # iterate over each record in the binary stream
    for record_type, record_data in yield_record(trace_stream,
                                                 size=RECORD_LENGTH):
            new_record = record(record_data)

    trace.append(new_record)
Run Code Online (Sandbox Code Playgroud)

然后让记录类构造函数执行确定它是什么类型的记录并创建适当的类实例的工作.理想情况下,我的"主要"例程不需要知道记录类型?

有没有办法做到这一点?

Kat*_*iel 6

存储映射会更简单

record_types = {SEN_RECORD: sen_record,
                DSP_RECORD: dsp_record,
                USO_RECORD: uso_record,
                SDM_RECORD: sdm_record,
                DOC_RECORD: doc_record,
                DAT_RECORD: dat_record,
                LAT_RECORD: lat_record,
                SWI_RECORD: swi_record,
                FTL_RECORD: ftl_record}
Run Code Online (Sandbox Code Playgroud)

在某处,并使用它来查找正确的记录类型.(请注意,您可以这样做,因为类只是对象,因此您可以将它们放在字典中.)

具体来说,你会这样做

new_record = record_types[record_type](record_data)
Run Code Online (Sandbox Code Playgroud)

有更复杂的方法(例如,如果您希望动态创建子类并在创建时自动注册其超类),但在您的情况下无需使用它们.