你的想法应该按原样工作。请确保您安装了 Hydra 版本 >= 1.1,然后试一试:
# foo/bar.yaml
_target_: mod.ChildClass
a: 0
b: 1
# config.yaml
defaults:
- foo: bar.yaml
_target_: mod.MainClass
c: 2
d: ${foo.a}
# mod.py
class ChildClass:
def __init__(self, a, b):
print(f"Child {a=} {b=}")
class MainClass:
def __init__(self, c, d, foo):
print(f"Child {c=} {d=} {foo=}")
# app.py
import hydra
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
@hydra.main(config_path=".", config_name="config")
def run(cfg: DictConfig):
instantiate(cfg)
if __name__ == "__main__":
run()
$ python app.py
Child a=0 b=1
Child c=2 d=0 foo=<mod.ChildClass object at 0x7f675436b130>