Python Forum
How I can fill class members?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How I can fill class members?
#1
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  associating members in a list to more than one features rezagholi 0 569 Mar-09-2023, 03:33 PM
Last Post: rezagholi
  Class Instances overriding class members and attributes. Leaf 7 6,806 Nov-29-2017, 06:08 AM
Last Post: Leaf

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020