이진 로그 파일을 구문 분석하고 있습니다. 로그 파일은 다음과 같이 형식화됩니다. 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)
경우 sen_record, dsp_record, uso_record 등 일반적인 기록 클래스의 모든 하위 클래스가
내가하고 싶은 무엇것은 다음은 있습니다 :
레코드 클래스 생성자에게 레코드 유형을 결정하고 적절한 클래스 인스턴스를 만드는 작업을 수행하게하십시오. 이상적으로 나의 "메인"루틴은 레코드 유형에 대해 알 필요가 없다.
이렇게 할 방법이 있습니까?
당신은'기록을 오버라이드 (override) 할 수있을 것 '['__new__'] (http://docs.python.org/reference/datamodel.html#object.__new__) 메서드를 사용하여 하위 클래스의 인스턴스를 반환 할 수 있습니다. – Darthfett
그런데 파이썬의 ['struct'] (http://docs.python.org/library/struct.html) 모듈에서 이진 데이터의 압축을 처리 했습니까? – katrielalex
@katrielalex 각 레코드 유형이 데이터를 다르게 해석하므로 각 레코드 하위 클래스의 생성자에서 struct 모듈을 사용하고 있습니다. – ACRL