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

标签 python python-3.x

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

相关文章:

python - 不同图像的相同 fc6 响应

python - 在Python中提取文本特征的最佳方法是什么

python - 引用纯虚方法

python - 如何升级odoo中的python版本

python - 属性错误: 'int' object has no attribute 'view' (1)

python - 将 Python 字典写入 CSV

Python ValueError 是否可以在不进行字符串解析的情况下获得不正确的值?

python - 在 python 3.4 上逐行读取文本文件

MySQL 测试数据库失败

Python/LXML - 从 etree 获取 "grandchildren"