-2

I want to initialize an instance with values from a database. I know the class name, because its the same as the table name.

class MyClass():
    def __init__(self, arg1, arg2, arg3):
          ...

values = (arg1, arg2, arg3)
className = "MyClass"

instance = ?

Thanks for helping.

Abu Bakr
  • 3
  • 1
  • Classes are first-class values; if you can avoid the string and just take a reference to the class, do that. `className = MyClass; instance = className(*values)`. If you *must* get a string for some reason, set up your own dict mapping expected strings to class references, like `d = {'MyClass': MyClass}`. – chepner Oct 17 '22 at 13:04

1 Answers1

0

I would use a metaclass to register every instance of a database model, with a dictionary to get a class, given a name:

class Models(type):
    classes = {}

    def __new__(cls, clsname, bases, attrs):
        newclass = super(Models, cls).__new__(cls, clsname, bases, attrs)
        Models.register(newclass)  # here is your register function
        return newclass

    @classmethod
    def register(cls, new_class):
        Models.classes[new_class.__name__] = new_class


class MyClass(metaclass=Models):
    def __init__(self, arg1, arg2, arg3):
          ...


values = ("a", "b", "c")
className = "MyClass"

instance = Models.classes.get(className)(*values)
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
  • Thanks a lot! Thats a lot of new stuff for me, but it works and I'm trying now to understand. :) – Abu Bakr Oct 17 '22 at 14:08
  • @AbuBakr Metaclasses are pretty advanced and can be confusing to understand, but are useful for stuff like this – Tom McLean Oct 17 '22 at 14:40