math4tots
math4tots

Reputation: 8869

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

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

Upvotes: 4

Views: 186

Answers (2)

mgilson
mgilson

Reputation: 310227

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)

Upvotes: 5

Ihor Kaharlichenko
Ihor Kaharlichenko

Reputation: 6270

Pretty much the same as in Java:

y = x.__class__()

Upvotes: 2

Related Questions