【发布时间】:2019-04-09 05:07:42
【问题描述】:
以下代码可在 Python 2.7 中使用 _x.__dict__['c']=8
class _x:
def __init__(self):
self.a = 6
self.b = 7
_x.__dict__['c']=8
print("good!")
y=_x()
print(y.__dict__)
print(_x.__dict__)
输出:
good!
{'a': 6, 'b': 7}
{'c': 8, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x00000000049227B8>}
以上代码不适用于 Python 3.6
_x.__dict__['c']=8 出现错误:
TypeError Traceback (most recent call last)
<ipython-input-5-b4146e87f5a4> in <module>()
6 print("good!")
7
----> 8 y=_x()
9 print(y.__dict__)
10 print(_x.__dict__)
<ipython-input-5-b4146e87f5a4> in __init__(self)
3 self.a = 6
4 self.b = 7
----> 5 _x.__dict__['c']=8
6 print("good!")
7
TypeError: 'mappingproxy' object does not support item assignment
有什么建议吗?
【问题讨论】:
-
为什么要通过
__dict__?你只是不知道setattr吗? -
你为什么要这样做?对于新构造而言,仅在类上设置值通常是一个非常糟糕的主意(在少数情况下有意义的情况是当您对实例进行编号等时,但在这种情况下,应使用基值定义类变量在定义时)。这闻起来like an XY problem。
-
找到了解决方案:
_x.c = 8有效。 -
user2357112,ShadowRanger:我正在将一个 python 应用程序(由另一位作者)从 2 转换为 3。只想让它现在工作,然后弄清楚“为什么”。感谢您的 cmets。
标签: python