我在我的def convert(dictionary类中有一个助手函数( helper function,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 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__中定义的函数?
发布于 2020-08-24 08:12:17
在每次调用__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。
https://stackoverflow.com/questions/63556776
复制相似问题