1

Suppose that we have an object x, but we do not know which class x is instantiated from. We want to create a new object y of the same type as x.

If we knew which class x was instantiated from, we could simply call the class constructor/initializer:

y = NameOfClass()

However, we do not know the name of the class x is instantiated from.

The main question can be broken down into two sub-questions:

1) How do I find out what datatype x is?
2) Given a datatype (stored somewhere in the computer) how do I create a new object of that type?

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42

1 Answers1

0
NameOfClass = type(x)
y = NameOfClass()
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • 1
    That's assuming the class actually *has* a constructor that works that way. – user2357112 Sep 22 '17 at 20:31
  • What if it takes parameters? You can’t assume this will work. The `__repr__` *might*, if correctly constructed, show you how to recreate at least some of the state, but there’s no guarantee. – jonrsharpe Sep 22 '17 at 20:36