gpt4 book ai didi

python - 如何在python中更改对象的类型

转载 作者:行者123 更新时间:2023-12-04 09:05:01 26 4
gpt4 key购买 nike

来自 pydocs

Like its identity, an object’s type is also unchangeable. [1]


来自 footnote

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.


什么情况下我们可以改变对象的类型以及如何改变它

最佳答案

class A:
pass

class B:
pass

a = A()

isinstance(a, A) # True
isinstance(a, B) # False
a.__class__ # __main__.A

# changing the class
a.__class__ = B

isinstance(a, A) # False
isinstance(a, B) # True
a.__class__ # __main__.B
但是,我不记得它可以提供帮助的真实示例。通常,类操作是在创建类(不是类的对象)时由装饰器或元类完成的。例如, dataclasses.dataclass是一个装饰器,它接受一个类并在它的基础上构造另一个类(参见 the source code)。

关于python - 如何在python中更改对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63465112/

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