繁体   English   中英

如何在Python 3中使用__dict__向类的__init __()中的类添加属性?

[英]How to add attributes to a class in __init__() of the class with __dict__ in Python 3?

以下代码在_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__)

输出:

good!
{'a': 6, 'b': 7}
{'c': 8, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x00000000049227B8>}

上面的代码在_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

有什么建议么?

您尝试使用非公共接口有什么原因吗? 如果出于某种原因要在实例化期间设置类属性,请尝试

class A:
    def __init__(self):
        self.__class__.k = 1

如果要动态设置访问权限,请使用setattr

此答案中描述的变异性背后的原因

您可以通过在变量名称之前指定类名称来设置类变量。

更改:

_x.__dict__['c']=8

至:

_x.c=8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM