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

标签 python python-datamodel

我希望能够做到:

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

相关文章:

python - PySpark 中的特征选择

python minidom : 'NoneType' object has no attribute 'data' from url

python - 如何获取所有可能的响应模式的容器名称?

python - Python 中的元类是什么?

python - 一切都大于无吗?

python - 以声明方式设置类 __name__

javascript - Flask WTForms 的自定义属性

python - 如何为每个配置文件配置 PIP 以使用代理(带身份验证)?

python - 为什么将 Counter 的 __init__ 方法称为描述符?

python - 在 Python 中遍历列表时删除元素