from pydocs
Like its identity, an object’s type is also unchangeable. [1]
from footnote
It is possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.
What are the cases when we can change the object's type and how to change it
class A:
pass
class B:
pass
a = A()
isinstance(a, A) # True
isinstance(a, B) # False
a.__class__ # __main__.A
# changing the class
a.__class__ = B
isinstance(a, A) # False
isinstance(a, B) # True
a.__class__ # __main__.B
However, I can't recall real-world examples where it can be helpful. Usually, class manipulations are done at the moment of creating the class (not an object of the class) by decorators or metaclasses. For example, dataclasses.dataclass is a decorator that takes a class and constructs another class on the base of it (see the source code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With