Under what circumstances is it possible, and when is it impossible, to assign to an instance's __class__
attribute in Python?
Error messages such as TypeError: __class__ assignment: only for heap types
don't really do it for me.
Use the setattr() Function to Set Attributes of a Class in Python. Python's setattr() function is used to set values for the attributes of a class. In programming, where the variable name is not static, the setattr() method comes in very handy as it provides ease of use.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
The __set__() method is invoked when the value is set to the attribute, and unlike the __get__() method, it returns nothing. It has two arguments apart from the descriptor object itself, i.e., the instance which is the same as the __get__() method and the value argument, which is the value you assign to the attribute.
You can only assign to the __class__
attribute of an instance of a user-defined class (i.e. defined using the class
keyword), and the new value must also be a user-defined class. Whether the classes are new-style or old-style does not matter. (You can't mix them, though. You can't turn an old-style class instance into a new-style class instance.) See also this issue in the Python bug tracker, which also complains that the error message is somewhat hard to understand.
Just to add what Rafe said in the above comment: Never do this in production.
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