gpt4 book ai didi

python - 更改 python 对象的类(强制转换)

转载 作者:IT老高 更新时间:2023-10-28 21:02:01 26 4
gpt4 key购买 nike

关于这个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

我想我改变了typef2 .
怎么了,我错过了什么?

最佳答案

该页的脚注:

[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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com