How to create a new instance of the same class as another object?

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.

+4
source share
1 answer

Calling type(x) definitely the canonical way to create a new instance of exactly the same type as x . However, what arguments for passing this call are not given, since the "signature" (the number and types of arguments passed in the call) changes with each other type; therefore, if you don’t know what type may be, you need more introspection for this purpose (as well as some kind of rule or heuristic about which all the arguments you want to pass as soon as you determine, for example, that you can pass any a number from 0 to 3 and that the optional / keyword names are: "y", "z", "t" ... obviously, it is impossible to establish a general rule here!).

So, can you clarify (as soon as the type to instantiate is easy to determine ;-) how are you going to solve complex problems that you don’t even mention? What restrictions can you accept in a type signature? Do you need to do any sanity checks, or is it ok to just raise a TypeError by calling the wrong type or number of arguments? Etc, etc .... without additional information about this character, your question simply does not lend itself to proving an answer that can really be used in the real world!)

+6
source

All Articles