Python Forum

Full Version: How I can fill class members?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If I set the class fields in the __init__ method, they will be set in every time when object is created, which is incorrect. At that not all classes have method __init__ (for example, singleton).

class _AbstractInserter(metaclass=ABCMeta):
    TABLE_NAME: str
    MAPPING = _AbstractInserter._create_mapping()
    CODE_SQL = _AbstractInserter._create_code_sql()
       
    @classmethod
    @abstractmethod
    def _create_mapping(cls) -> dict:pass
    
    @classmethod
    def _create_code_sql(cls) -> str:
        code_sql = ''
        for key, value in cls.MAPPING.items():
            code_sql += key + '=' + value
        return code_sql

class MyInserter(_AbstractInserter):
    TABLE_NAME = 'MyTable'

    @classmethod
    def _create_mapping(cls) -> dict:
        mapping = {}
        mapping[cls.TABLE_NAME] = 'id'
        return mapping
Output:
MAPPING = _AbstractInserter._create_mapping() NameError: name '_AbstractInserter' is not defined
I get this error even if I use this code:
from __future__ import annotations
How can I do this?