class ClassA: pass
mytype = type(ClassA)
Using mytype, how do you create an instance of ClassA?
Note that I’m NOT looking for this as my answer 🙂
instance = ClassA()
I know that in this example, that’s all you need to do but suppose that you have this type (mytype), you don’t know anything about it, and you need to create an instance of it.
I tried just calling mytype() and it returns an error stating that type() takes 1 or 3 arguments. I imagine these arguments may be related to any arguments you’d want to pass into the init method of the object being created.
Note: I’ve seen a number of questions asked about how to create an object given a string representing its fully qualified name. Note that here, I already have a type so it’s a bit different? I think?
I had hoped that I could do the equivalent of the following .NET code:
class A {}
class Program
{
static void Main(string[] args)
{
Type type = typeof(A);
// Given the type, I can create a new instance
object new_instance = Activator.CreateInstance(type);
}
}
I had assumed that in Python, type(ClassA) gave something back that I could later use to create an instance of ClassA. Looks like I misunderstood type in Python.
If you use a new style class it, this will work: