Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to an instance's __class__ attribute in Python

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.

like image 994
porgarmingduod Avatar asked Jan 29 '11 17:01

porgarmingduod


People also ask

How do you give a class attributes in Python?

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.

What does __ class __ mean in Python?

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

What is __ set __ in Python?

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.


1 Answers

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.

like image 163
Sven Marnach Avatar answered Oct 11 '22 03:10

Sven Marnach