Having a object x
which is an instance of some class how to create a new instance of the same class as the x
object, without importing that all possible classes in the same namespace in which we want to create a new object of the same type and using isinstance
to figure out the correct type.
For example if x
is a decimal number:
>>> from decimal import Decimal
>>> x = Decimal('3')
>>> x
Decimal('3')
how to create new instance of Decimal
. I think the obvious thing to do would be either of these:
>>> type(x)('22')
Decimal('22')
>>> x.__class__('22')
Decimal('22')
Since __class__
will not work on int
for example:
>>> 1.__class__
File "<stdin>", line 1
1.__class__
Is it good practice to use type
to achieve this, or is there some other ways or more caveats when using this approach for creating new objects?
Note:
There was an answer that is now deleted that gave a right way to get __class__
of int
.
>>> (1).__class__
<type 'int'>
Use case
The question is mostly theoretical, but I am using this approach right now with Qt to create new instances of QEvent
. For example, since the QEvent
objects are consumed by the application event handler in order to post the event to QStateMachine
you need to create a new instance of the event otherwise you get runtime error because the underlying C++ object get deleted.
And since I am using custom QEvent
subclasses that all share the same base class thus objects accept same predefined set of arguments.