首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何引用__init__超类中定义的函数

如何引用__init__超类中定义的函数
EN

Stack Overflow用户
提问于 2020-08-24 07:49:35
回答 1查看 59关注 0票数 0

我在我的def convert(dictionary类中有一个助手函数( helper function,def convert(dictionary)来帮助配置设置。定义如下:

代码语言:javascript
复制
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__中进行如下调用:

代码语言:javascript
复制
        self.input = convert(self._config["input"])
        self.output = convert(self._config["output"])
        self.build = convert(self._config["build_catalog"])

由于我有不止一个吐露要建立,我想从他的阶级继承如下:

代码语言:javascript
复制
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"])

但是,我不能从父类访问convert。我也尝试过这样做:

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

这似乎也行不通。

因此,问题是如何从子类访问在super().__init__中定义的函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-24 08:12:17

在每次调用__init__时都会创建一个新函数,并将其丢弃,它不存在于该函数之外。注意,这也适用于namedtuple('Config', dictionary.keys())(**dictionary)创建的类。继续创建所有这些不必要的类确实不太好,这完全违背了namedtuple用于创建内存高效记录类型的目的。在这里,每个实例都有自己的类!

下面是您应该如何定义它的方法:

代码语言:javascript
复制
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"])

虽然在这一点上,仅仅使用

代码语言:javascript
复制
Config(**self._config["input"])

等,然后丢弃助手convert

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63556776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档