Задать вопрос
  • Как правильно структурировать функции датакласса?

    @Ninzalo Автор вопроса
    В итоге, своими силами получилось нечто такое:
    class Main_key:
        def __init__(self, outer) -> None:
            self.outer = outer
    
        def change_main_key(self, main_key: str):
            if not self.outer.main_key:
                error_str = f"Outer class don't have .main_key param"
                raise Exception(error_str)
            old_main_key = self.outer.main_key
            self.outer.main_key = main_key
            print(
                f"Main key '{old_main_key}' was changed to '{self.outer.main_key}'"
            )
    
    
    class Keys:
        def __init__(self, outer) -> None:
            self.outer = outer
    
        def add_key(self, key: str | List[str]):
            if isinstance(key, list):
                for k in key:
                    self.append_keys(key=k)
                return
            if key in self.outer.keys:
                error_str = f"Key value '{key}' already exists: {self.outer.keys}"
                raise ValueError(error_str)
            self.outer.keys.append(key)
            print(f"Keys list was appended by {key}")
    
    
    @dataclass()
    class My_class:
        main_key: str = "type"
        keys: List[str] = field(default_factory=list)
        main_key_funcs: Main_key | None = None
        keys_funcs: Keys | None = None
    
        def get(self):
            self.main_key_funcs = Main_key(outer=self)
            self.keys_funcs = Keys(outer=self)
    
    
    c = My_class()
    c.get()
    c.main_key_funcs.change_main_key(main_key="subtype")
    c.keys_funcs.add_key('first_key')
    c.keys_funcs.add_key('second_key')
    print(c)

    Работает превосходно, так, как и планировалось
    Main key 'type' was changed to 'subtype'
    Keys list was appended by first_key
    Keys list was appended by second_key
    My_class(main_key='subtype', keys=['first_key', 'second_key'], main_key_funcs=<__main__.Main_key object at 0x102acd1d0>, keys_funcs=<__main__.Keys object at 0x102acd250>)

    Можно ли как-то улучшить? Открыт к предложениям
    Ответ написан