Python Forum
How I can fill class members? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How I can fill class members? (/thread-16093.html)



How I can fill class members? - AlekseyPython - Feb-14-2019

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?