如何引用 __init__ super class 中定义的函数

How to reference function defined in __init__ super class

我的 __init__ class 中有一个帮助函数 (def convert(dictionary) 来协助配置设置。定义如下:

class Configuration:

    def __init__(self, config_file=None, config=None):

        if config_file is not None:
            with open(config_file) as in_file:
                self._config = yaml.load(in_file, Loader=yaml.FullLoader)
        elif config is not None:
            self._config = config
        else:
            raise ValueError("Could not create configuration. Must pass either location of config file or valid "
                             "config.")

        def convert(dictionary):
            return namedtuple('Config', dictionary.keys())(**dictionary)

这让我可以在 __init__ 内拨打电话,如下所示:

        self.input = convert(self._config["input"])
        self.output = convert(self._config["output"])
        self.build = convert(self._config["build_catalog"])

因为我要设置多个配置,所以我想继承他的 class 如下:

class BuildConfiguration(Configuration):

    def __init__(self, config_file=None, config=None):

        super().__init__(config_file, config)

        self.input = convert(self._config["input"])
        self.output = convert(self._config["output"])
        self.build = convert(self._config["build_catalog"])

但是,我无法从父 class 那里获得对 convert 的访问权限。我也试过这个:

self.input = super().__init__.convert(self._config["input"])

这个好像也行不通。

所以问题是如何从子 classes 访问 super().__init__ 中定义的函数?

你不能。每次调用 __init__ 都会创建一个新函数,然后将其丢弃,它不存在于函数之外。请注意,这也适用于 namedtuple('Config', dictionary.keys())(**dictionary) 创建的 class。一直创造这些不必要的class确实不好,这完全违背了namedtuple创造memory-efficientrecord-types的目的。在这里,每个实例都有自己的 class!

您应该如何定义它:

Config = namedtuple('Config', "foo bar baz")

def convert(dictionary): # is this really necessary?
    return Config(**dictionary) 

class Configuration:

    def __init__(self, config_file=None, config=None):

        if config_file is not None:
            with open(config_file) as in_file:
                self._config = yaml.load(in_file, Loader=yaml.FullLoader)
        elif config is not None:
            self._config = config
        else:
            raise ValueError("Could not create configuration. Must pass either location of config file or valid "
                             "config.")

        self.input = convert(self._config["input"])
        self.output = convert(self._config["output"])
        self.build = convert(self._config["build_catalog"])

虽然在这一点上,使用

似乎更干净
Config(**self._config["input"])

etc 而不是帮手 convert.