Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change object's type in python

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

like image 656
CrazyPythonProgrammer Avatar asked Oct 27 '25 04:10

CrazyPythonProgrammer


1 Answers

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

like image 90
Gram Avatar answered Oct 28 '25 18:10

Gram