在Python中分配实例的__class__属性 [英] Assigning to an instance's __class__ attribute in Python
问题描述
在什么情况下,什么时候不可能在Python中分配实例的__class__
属性?
Under what circumstances is it possible, and when is it impossible, to assign to an instance's __class__
attribute in Python?
诸如TypeError: __class__ assignment: only for heap types
之类的错误消息对我而言并不是真的.
Error messages such as TypeError: __class__ assignment: only for heap types
don't really do it for me.
推荐答案
您只能分配给用户定义的类(即使用class
关键字定义的)实例的__class__
属性,值也必须是用户定义的类.这些类是新样式还是旧样式都没有关系. (但是,您不能将它们混合使用.您不能将旧式类实例转换为新式类实例.)另请参见 Python错误跟踪器中的="noreferrer">此问题,它还抱怨该错误消息有些难以理解.
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.
只需添加Rafe在上面的评论中所说的话:绝对不要在生产中这样做.
Just to add what Rafe said in the above comment: Never do this in production.
这篇关于在Python中分配实例的__class__属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!