以类似的方式初始化不同的类

以类似的方式初始化不同的类

问题描述:

我有不同的类,我需要以几乎相同的方式部分初始化。 init函数接受输入文件路径和/或一些numpy数据。以类似的方式初始化不同的类

class InertialData1: 
    def __init__(self, file=None, data=None): 
     # --- this is the (almost) common part --- 
     if file is None: 
     self.file = 'Unknown path to file' 
     else: 
     self.file = file 
     assert isinstance(self.file, str) 

     if data is None: 
     self.data = read_logfile(file, 'a_token') 
     else: 
     self.data = data 
     assert isinstance(self.data, np.ndarray) 
     # --- end of the common part --- 

     # Here other stuff different from class to class 

在read_logfile()函数(外部函数)也从类改变为类的标记。

class InertialData2: 
    def __init__(self, file=None, data=None): 
     # here the common code as above, but with 'another_token' instead of 'a_token' 
     # here other stuff 
... 

当然,在所有类定义中写入相同的行是不行的。

可能的解决方案。

我想过定义这样

def initialize(file, data, token): 
    if file is None: 
     file = 'Unknown path to file' 
    else: 
     file = file 
    assert isinstance(file, str) 

    if data is None: 
     data = read_logfile(file, token) 
    else: 
     data = data 
    assert isinstance(data, np.ndarray) 
return file, data 

外部函数,那么我可以用它的每个类的初始化方法像这里面:

class InertialData1: 
    def __init__(self, file=None, data=None): 
     self.file = file 
     self.data = data 
     self.file, self.data = initialize(self.file, self.data, token='a_token') 

这种方式似乎是工作。我只是觉得它不是最好的方法,或者不是pythonic,我希望从你的答案中学到一些东西:) 谢谢

你应该能干(不要重复自己)你的代码使用类继承:

class InertialData: 
    def __init__(self, file=None, data=None): 
    # --- this is the common part --- 
    if file is None: 
     self.file = 'Unknown path to file' 
    else: 
     self.file = file 
    assert isinstance(self.file, str) 

    def init_data(self, token, data): 
    if data is None: 
     self.data = read_logfile(self.file, token) 
    else: 
     self.data = data 
    assert isinstance(self.data, np.ndarray) 

class InertialData1(InertialData): 
    def __init__(self, file=None, data=None): 
    # --- this is the different part --- 
    super().__init__(file=file, data=data); 
    self.init_data('token_a', data) 

注意的几件事情:

你可以做一个“通用”类,InertialData,具有重复功能。然后,所有的自定义类都可以从通用类继承。请参阅类InertialData1如何将InertialData作为参数?

在从InertialData继承所有类,你可以调用super,这将调用父类的,在这种情况下是InertialData__init__方法。

初始化每个类具有不同标记的数据的代码位已被拉入以令牌作为参数的函数中。现在,您可以拨打initialize_data('token_a')中的任何继承自InertialData的任何类的__init__函数。

我将您的类重命名为以大写字母开头(正如Python的惯例)。

+0

感谢您的回复。但它似乎并没有像这样工作。 类型错误:超级不采取关键字参数 – Robyc

+0

对不起,我忘了'super'自动重用那些在传递的参数我也意识到,您将需要通过'data'到'init_data'方法,所以我加了。那个代码太 –

+0

'超'独自也是行不通的。 'super().__ init __(file,data)'正在工作。 但是,我不确定如何调用基本初始化函数是一种很好的做法。 – Robyc