4

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();
1
  • Keep in mind that class is a flexible concept in Python, given the ability to use custom metaclasses and descriptors. Commented Aug 16, 2012 at 0:22

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

6 Comments

type won't work for old style classes. Also, this probably won't work for metaclasses.
Thanks for the comment about old style classes (I never use them, so I didn't think of that.) As far as metaclasses are concerned, I don't use those either, so I can't help with that one. It's good to know where my solution might fail though. Thanks for pointing that out too.
I can't see why there's a problem with metaclasses. The problem to me is that you're calling the constructor without arguments and it may require some.
Like the OP's question, this assumes the constructor requires no arguments.
@JBernardo -- Of course it is assumed here that __init__ recieves no arguments (other than the obligatory self). I would assume you would have the same problem in Java?
|
2

Pretty much the same as in Java:

y = x.__class__()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.