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