1

The aim of the following code is to dynamically create a class based on the user's input.

class BaseClass:
    def __init__(self):
        self.placeholder = ""


if __name__ == '__main__':
    className = input("Please enter the name of new class: ")
    baseClass = input("Please enter name of base class: ")
    try:
        newClass = type(className, tuple(baseClass), {})
        print(f"Class {newClass} Created")
    except TypeError as e:
        print(e)

However, upon entering the input:

NewClass
BaseClass

I receive the follwing exception:

metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Why the program doesn't recognized the class BaseClass? What would be the proper use of the type function?

Note: I'm running python v3.9.6.

Example program output snippet: enter image description here

1
  • 1
    baseClass is a string not a reference to the actual class itself Commented Aug 7, 2021 at 11:57

1 Answer 1

1

Bases have to be classes not strings, so you need to get the class from string name:

class BaseClass:
    def __init__(self):
        self.placeholder = ""


if __name__ == '__main__':
    #className = input("Please enter the name of new class: ")
    #baseClass = input("Please enter name of base class: ")

    className = 'Foo'
    baseClass = 'BaseClass'

    baseClassObj = globals().get(baseClass, None)
    if baseClassObj:
        newClass = type(className, (baseClassObj, ), dict())
        print(f"Class {newClass} Created")
    else:
        print('baseClass not found!')

Out:

Class <class '__main__.Foo'> Created
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.