关于这个python doc page它说:
Like its identity, an object’s type is also unchangeable.
我试试这个脚本,
#!python3
class Foo:
num = 1
pass
class Bar:
num = 2
pass
f1,f2= Foo(), Foo()
f2.__class__ = Bar
print( type(f1), type(f2), f1.num, f2.num )
结果显示:
<class '__main__.Foo'> <class '__main__.Bar'> 1 2
我想我改变了type
的 f2
.
怎么了,我错过了什么?
最佳答案
该页的脚注:
[1] 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.
如果你尝试将f2的__class__
改为list
:
f2.__class__ = list
引发类型错误:
TypeError: __class__ assignment: only for heap types
关于python - 更改 python 对象的类(强制转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15404256/