1 回答

TA貢獻1862條經驗 獲得超7個贊
你不能。每次調用都會創建一個新函數,__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"])
etc 而不是 helper convert。
添加回答
舉報