[英]How to add attributes to a class in __init__() of the class with __dict__ in Python 3?
The following code works in Python 2.7 with _x.__dict__['c']=8
以下代码在_x.__dict__['c']=8
Python 2.7中有效
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__)
Output: 输出:
good!
{'a': 6, 'b': 7}
{'c': 8, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x00000000049227B8>}
The above code does not work in Python 3.6 with _x.__dict__['c']=8
and got errors: 上面的代码在_x.__dict__['c']=8
Python 3.6中不起作用,并出现错误:
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
Any suggestions? 有什么建议么?
Is there any reason you're trying to use non-public interface? 您尝试使用非公共接口有什么原因吗? If for some reason you want to set class attribute during instantiation, try 如果出于某种原因要在实例化期间设置类属性,请尝试
class A:
def __init__(self):
self.__class__.k = 1
If you want to set access dynamically, use setattr
如果要动态设置访问权限,请使用setattr
Reasoning behind mutability changes described in this answer 此答案中描述的变异性背后的原因
You can set a class variable by specifying the class name before the variable name. 您可以通过在变量名称之前指定类名称来设置类变量。
Change: 更改:
_x.__dict__['c']=8
to: 至:
_x.c=8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.