我有一个函数可以获取一些数据并将其组织到不同的容器中。这是由不同的解析器为不同的输入数据完成的。
class ParsingObject(object):
def __init__(self):
self.organized_data_1 = OrganizedContainer1()
self.organized_data_2 = OrganizedContainer2()
self.organized_data_3 = OrganizedContainer3()
def parse_data(format, data):
if format == 'format1':
# Some code that takes data, and populate containers
self.organized_data_1 = x
self.organized_data_2 = y
self.organized_data_3 = z
if format == 'format2':
# Some code that takes data, and populate containers differently
self.organized_data_1 = y
self.organized_data_2 = z
self.organized_data_3 = x
我想将所有解析器存储在一个单独的文件中,然后将它们导入到parse_data函数中。
该函数需要访问实例变量(organized_data_1-3)才能填充它们。
class ParsingObject(object):
def __init__(self):
self.organized_data_1 = OrganizedContainer1()
self.organized_data_2 = OrganizedContainer2()
self.organized_data_3 = OrganizedContainer3()
def parse_data(format, data):
import .parsers
if format == 'format1': parsers.parser1(data)
if format == 'format2': parsers.parser2(data)
解析器类似
def parser1(data):
self.organized_data_1 = x
self.organized_data_2 = y
self.organized_data_3 = z
我希望将解析器放在另一个函数中,以便更方便地添加额外的解析器并防止主对象混乱。我应该将对象传递给解析器吗?
def parser1(self,data):
self.organized_data_1 = x
self.organized_data_2 = y
self.organized_data_3 = z
还是有另一种方式吗?如果我这样设置,我最终会导致循环模块导入。