Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance, I already have the type

Tags:

python

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.

like image 418
Matthew Lund Avatar asked Dec 07 '11 19:12

Matthew Lund


People also ask

How do I create an instance of a type?

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.

How do I get the instance of a type in C#?

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 ();

How do I create a new instance in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

Can you create an instance of a class?

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.


2 Answers

If you use a new style class it, this will work:

class ClassA(object):
    pass

o = ClassA()
mytype = type(o)
new_object = mytype()
like image 159
Chris Lacasse Avatar answered Sep 19 '22 12:09

Chris Lacasse


Is lazyr says, it is not possible with type. Maybe what you could use is something like

class ClassA: pass
myclass = ClassA
instance = myclass()
like image 38
silvado Avatar answered Sep 19 '22 12:09

silvado