Say I have a class, which has a number of subclasses.
I can instantiate the class. I can then set its __class__
attribute to one of the subclasses. I hav
Assigning the __class__
attribute is useful if you have a long time running application and you need to replace an old version of some object by a newer version of the same class without loss of data, e.g. after some reload(mymodule)
and without reload of unchanged modules. Other example is if you implement persistency - something similar to pickle.load
.
All other usage is discouraged, especially if you can write the complete code before starting the application.
How "dangerous" it is depends primarily on what the subclass would have done when initializing the object. It's entirely possible that it would not be properly initialized, having only run the base class's __init__()
, and something would fail later because of, say, an uninitialized instance attribute.
Even without that, it seems like bad practice for most use cases. Easier to just instantiate the desired class in the first place.