from dataclasses import dataclass
from typing import List
@dataclass()
class My_class:
value: str
main_key: str = "type"
keys: List[str] = field(default_factory=list)
def change_main_key(self, main_key: str):
self.main_key = main_key
print(f"Main key was changed to '{self.main_key}'")
def add_key(self, key: str | List[str]) -> None:
if isinstance(key, list):
for k in key:
self.add_key(key=k)
return
if key in self.keys:
raise ValueError("Key value already exists in keys")
self.keys.apppend(key)
print(f"Keys list was appended by '{key}'")
c = My_class(value="my_value")
c.main_keys.change_main_key(main_key='subtype')
c.keys.add_key(key=["first_key", "second_key"])
print(c)
> Main key 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"])
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>)