Home > Blockchain >  Declaring class name in variable
Declaring class name in variable

Time:12-29

I am building a project and I am trying to declare class's name in variable before declaring variable.

But when I declare variable like :-

klassName = MyClass

class klassName(models.Model):
    title = models.CharField(max_length=30)

then it is assigning with KlassName Not the variable I referenced to it.

Then I tried :-

className = 'MyClass'
klass = type(className, (object,), {'msg': 'foobarbaz'})
x = className()

class x():
    title = models.CharField(max_length=30)

it is showing

NameError: name 'className' is not defined

I didn't find any documentation of declaring.

I did follow according to This. But none is seemed to work for me.

Any help would be much appreciated. Thank You in Advance.

CodePudding user response:

To create a class dynamically you can use the three argument form of type. To also dynamically create a variable or module member with the same name you can use globals() to create variables dynamically

globals()['className'] = type('className', (object,), {'foo': 'bar'})

To create a model dynamically may be slightly more complex but you can use an abstract base class to define all the fields/methods on for convenience

class Base(models.Model):
    foo = models.CharField(max_length=100)

    class Meta:
        abstract = True

globals()['className'] = type('className', (Base, ), {'__module__': Base.__module__})

CodePudding user response:

in your example:

klassName = MyClass

class klassName(models.Model):
    title = models.CharField(max_length=30)

klassName referenced to nothing, because MyClass is not defined. You can say:

MyClass = klassName

class klassName(models.Model):
    title = models.CharField(max_length=30)
  • Related