Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new instance from a class object in Python

Tags:

python

oop

I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object.

like image 201
ycseattle Avatar asked May 08 '11 00:05

ycseattle


People also ask

How do I create a new instance of a class?

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. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.

How do I create a new instance of an object?

Answer. To create a new instance of an object, we use the "new" keyword. This keyword creates a new instance of an object, which we can then assign to a variable, or invoke methods. For example, to create a new StringBuffer object, we would use the new keyword in the following way.

How do I get an instance of a class in Python?

There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.

What is a new instance in Python?

new instance means a new object with its own space in memory. most languages use a 'new' keyword so that it is explicit that the object is new and that the new instance's (object's) properties are not referenced/shared with another instance.


1 Answers

I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.

class k:   pass  a = k() k2 = a.__class__ a2 = k2() 

At this point, a and a2 are both instances of the same class (class k).

like image 104
xvf17 Avatar answered Sep 29 '22 09:09

xvf17