the list updated within a class

帅比萌擦擦* 提交于 2019-12-25 05:23:14

问题


class A(object):
    aalist = []
    ai = 0
    def __init__(self):
    self.ablist = list()
    def add(self):
        self.aalist.append(["a","a"])
        self.ablist.append(["b","b"])
        self.ai = self.ai + 1
class B(A):
    def __init__(self):
        A.__init__(self)
        self.bblist = list()
    def badd(self):
        self.bblist.append(['c','c'])
for i in range(1,4):
    c = B()
    c.add()
    c.badd()
    print c.aalist,c.ablist,c.bblist,c.ai

run these codes , the result prompts:

[['a', 'a']] [['b', 'b']] [['c', 'c']] 1
[['a', 'a'], ['a', 'a']] [['b', 'b']] [['c', 'c']] 1
[['a', 'a'], ['a', 'a'], ['a', 'a']] [['b', 'b']] [['c', 'c']] 1

I don't know why list get updated in the loop whereas the int seems to keeps static


回答1:


You're doing completely different operations with them. Note that you assign a new integer to self.ai when you do self.ai = self.ai + 1. When you work with the list, you work on it in place using append. Also note that since you're working with an int (which is immutable), you can't change it's value in place.

There's also evidence that you're exploring class variables vs. instance variables here. Note that in your example, ablist and bblist are instance variable whereas aalist is a class variable. You can access them all the same way within a method (self.XXlist), but when you mutate self.aalist, you'll mutate the version on the class. In other words, self.aalist is A.aalist will return True. This allows all instances of your class to share the same list. When one updates the list, all the other instances will know immediately (unless they bind an instance level attribute with the same name -- That variable will then take precedence in the attribute lookup).



来源:https://stackoverflow.com/questions/13070948/the-list-updated-within-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!