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.
How do you get a new object instance from a Type ? Just as an extra to anyone using the above answers that implement: ObjectType instance = (ObjectType)Activator. CreateInstance(objectType); Be careful - if your Constructor isn't "Public" then you will get the following error: > "System.
GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType ();
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor.
If you use a new style class it, this will work:
class ClassA(object):
pass
o = ClassA()
mytype = type(o)
new_object = mytype()
Is lazyr says, it is not possible with type
. Maybe what you could use is something like
class ClassA: pass
myclass = ClassA
instance = myclass()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With