1 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
你不能。每次調(diào)用都會(huì)創(chuàng)建一個(gè)新函數(shù),__init__然后將其丟棄,它不存在于函數(shù)之外。請(qǐng)注意,這也適用于由創(chuàng)建的類namedtuple('Config', dictionary.keys())(**dictionary)。繼續(xù)創(chuàng)建所有這些不必要的類確實(shí)不好,這完全違背了namedtuple創(chuàng)建內(nèi)存高效記錄類型的目的。在這里,每個(gè)實(shí)例都有自己的類!
以下是您應(yīng)該如何定義它:
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"])
雖然在這一點(diǎn)上,使用它似乎更干凈
Config(**self._config["input"])
etc 而不是 helper convert。
添加回答
舉報(bào)