4

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

  • Does this answer your question? [changing the class of a python object (casting)](https://stackoverflow.com/questions/15404256/changing-the-class-of-a-python-object-casting) – Tomerikoo Aug 18 '20 at 10:09

1 Answers1

2
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).

Gram
  • 341
  • 2
  • 10