更改 python 对象的类(铸造) [英] changing the class of a python object (casting)

查看:42
本文介绍了更改 python 对象的类(铸造)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个 python 文档页面上,它说:

与其身份一样,对象的类型也是不可更改的.

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__.Bar'>1 2

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

I think I changed the type of f2.
What's wrong, What am I missing?

推荐答案

那一页的脚注说:

[1] 在某些情况下可以改变一个对象的类型,在某些受控条件.不过,这通常不是一个好主意,因为如果处理它会导致一些非常奇怪的行为不正确.

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

If you try to change the __class__ of f2 to list:

f2.__class__ = list

引发了类型错误:

TypeError: __class__ assignment: only for heap types

这篇关于更改 python 对象的类(铸造)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆