gpt4 book ai didi

python - 何时何地以及如何更改对象的 __class__ attr?

转载 作者:太空狗 更新时间:2023-10-29 17:07:42 24 4
gpt4 key购买 nike

我希望能够做到:

>>> class a(str):
... pass
...
>>> b = a()
>>> b.__class__ = str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types

最佳答案

我是这样解决的:

>>> class C(str):
... def __getattribute__(self, name):
... if name == '__class__':
... return str
... else:
... return super(C, self).__getattribute__(name)
...
>>> c = C()
>>> c.__class__
<type 'str'>

关于python - 何时何地以及如何更改对象的 __class__ attr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3013280/

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