如何解决如何引用__init__超类中定义的函数
我在def convert(dictionary
类中有一个辅助函数(__init__
),以帮助进行配置设置。定义如下:
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 BuildConfiguration(Configuration):
def __init__(self,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__
中定义的函数?
解决方法
不能。每次调用__init__
都会创建一个新函数,并且将其丢弃,该函数不存在于该函数之外。注意,这也适用于由namedtuple('Config',dictionary.keys())(**dictionary)
创建的类。继续创建所有这些不必要的类确实不好,这完全破坏了namedtuple
的目的,即创建内存效率高的记录类型。在这里,每个实例都有自己的类!
这是您应如何定义它:
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"])
等,然后抛弃助手convert
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。