子类访问父类的父类具有超级属性,而无需重复参数

时间:2019-05-10 09:44:12

标签: python inheritance simplify

我想从子类访问父级属性,而不必一直重复Limit: 10参数

我尝试过不使用超级类,尝试过super().__init__,尝试过在父类或子类中设置默认值

让我说以下情况:

super().attribute

然后我有几个子类,如:

class GM2_setup_to_convert:

    #Class to define which file to convert
    def __init__(self, file_name, path_to_folder):
        self.file_name = file_name
        self.path_to_folder = path_to_folder
        self.file_to_convert = self.path_to_folder + self.file_name

,依此类推。现在,如果要实例化子类的实例,是否有一种方法可以避免每次实例化时都必须编写super()。 init (file_name,path_to_folder)参数(请参见下文)?

class Hardware_sheet(GM2_setup_to_convert):

    #Class to define hardware_sheet of file to convert
    def __init__(self, file_name, path_to_folder):
        super().__init__(file_name, path_to_folder)

        self.spec_excl_file_hardware = pd.read_excel(self.file_to_convert, sheet_name=' Hardware ', header=None)

class Expressions_cal(GM2_setup_to_convert):

    def __init__(self,file_name, path_to_folder):
        super().__init__(file_name, path_to_folder)

        self.spec_excl_file_cal_expr = pd.read_excel(self.file_to_convert, sheet_name=' Expression Calculation ', header=None, skiprows=[0, 1])

例如喜欢:

expr = Expressions_cal(file_name, path_to_folder)

或:

class GM2_setup_to_convert:

    #Class to define which file to convert
    def __init__(self, file_name=default, path_to_folder=default):
        self.file_name = file_name
        self.path_to_folder = path_to_folder
        self.file_to_convert = self.path_to_folder + self.file_name

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用完整路径作为参数。然后,如果要拆分它,则可以使用例如path, file_name = os.path.split()或类似的内容:

import os
class GM2_setup_to_convert:

    def __init__(self, path="default_path"):
        self.file_name = os.path.basename(path)
        self.path_to_folder = os.path.dirname(path)
        self.file_to_convert = path


class Expressions_cal(GM2_setup_to_convert):

    def __init__(self, path=None):
        if path:
            super().__init__(path)
        else:
            super().__init__()  # In this case defaul value from class above will be taken.

        self.spec_excl_file_cal_expr = pd.read_excel(self.file_to_convert, sheet_name=' Expression Calculation ', header=None, skiprows=[0, 1])

现在,您有两种创建Expressions_cal对象的方法。

obj1 = Expressions_cal('new_path_to_file')  # pass 'new_path_to_file' as parameter
obj2 = Expressions_cal()  # takes defaul parameter ('default_path') from parent class