zoukankan      html  css  js  c++  java
  • python中import list,dictionary常量在class实例化时遇到的坑

    事情大概是这样的:
    我定义了一个dict
    a = {'a':0,'b':1,'c':2}
    在另外一个python文件中import了上面的a
    from test import a
    class test1:
    def add(self):
    b = '3'
    a.update({'d': b})
    print(a)

    def add1(self):
    b = 4
    a.update({'e':b})
    print(a)

    if __name__ == '__main__':
    tst = test1()
    tst.add()
    tst.add1()
    我预想的是add和add1是分别将各自里面的key,value添加到a这个dict中去。结果,运行得到的却是:

    {'a': 0, 'b': 1, 'c': 2, 'd': '3'}

    {'a': 0, 'b': 1, 'c': 2, 'd': '3', 'e': 4}

    解决方案一:

    from test import a
    class test1:
    def add(self):
    b = '3'
         s = a.copy()
    s.update({'d': b})
    print(s)

    def add1(self):
    b = 4
         s = a.copy()
    s.update({'e':b})
    print(s)

    if __name__ == '__main__':
    tst = test1()
    tst.add()
    tst.add1()
    将import的dict进行复制,而不是直接在dict上进行操作(list同理)

    解决方案二:
    def getA():
      return {'a':0,'b':1,'c':2}

    from test import getA()
    class test1:
    def add(self):
    b = '3'
         s = getA()
    s.update({'d': b})
    print(s)

    def add1(self):
    b = 4
         s = get()
    s.update({'e':b})
    print(s)

    if __name__ == '__main__':
    tst = test1()
    tst.add()
    tst.add1()
    这个就是每次赋值的时候都调方法动态获取,避免在同一个实例化中传递了。
  • 相关阅读:
    1085 PAT单位排行
    安装MongoDB并且添加用户
    同源政策,发送请求时携带cookie信息
    博客园文章编辑时实现语法高亮
    template中的时间格式如何修改
    Node模块下载路径的更改设置
    JavaScript--遍历
    JavaScript--作用域
    JavaScript--arguments
    JavaScript--apply&call
  • 原文地址:https://www.cnblogs.com/zoulifeng2017/p/13819252.html
Copyright © 2011-2022 走看看