0

给定以下配置文件:

# foo/bar.yaml
_target_: ChildClass
a: 0
b: 1
# config.yaml
defaults:
- foo: bar.yaml

_target_: MainClass
c: 2
d: ${foo.a}  # this line doesn't work

我想构造一个MainClass类型的对象,它采用ChildClass类型的对象。ChildClass
的参数之一也用于MainClass的构造函数。

如何a使用参数插值读取子属性?

4

1 回答 1

0

你的想法应该按原样工作。请确保您安装了 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>
于 2021-12-15T07:02:43.543 回答