Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new instance of a Class given an instance in Python

Tags:

python

oop

In Python, if I have an object, say x, then how do I create a new object y so that x and y are of the same class?

In Java, the code I want would look something like this:

Object y = x.getClass().newInstance();
like image 203
math4tots Avatar asked Oct 25 '25 14:10

math4tots


2 Answers

You could probably do something like:

y = x.__class__()

or

y = type(x)()  #New style classes only

And, if you're wondering how to make a new style class, all you need to do is inherit from object (or use python 3.x)

like image 115
mgilson Avatar answered Oct 28 '25 02:10

mgilson


Pretty much the same as in Java:

y = x.__class__()
like image 28
Ihor Kaharlichenko Avatar answered Oct 28 '25 03:10

Ihor Kaharlichenko