类变量的行为根据其类型而不同(共享或不共享)

时间:2019-05-09 04:36:16

标签: python

数字和列表在用作类变量时的行为有所不同:数字不与实例共享,而列表变量却与实例共享。 (在相同条件下)有人可以解释发生了什么事吗?

Ps:已经问过这个问题(解释得不够清楚),并且它作为关于类变量的一般问题而重复出现。我问为什么在相同条件下数字和列表类变量之间会有区别。

class test_class:
    number = 0
    list = [8]
    def addnum(self, num):
        self.number = num
    def addlist(self, list):
        self.list.append(list)
object = test_class()
object.addnum(5)
object.addlist(6)

print(test_class.number)
print(object.number)

print(test_class.list)
print(object.list)

此打印:

0
5         (number variable is not shared)
[8, 6]    (list was shared)
[8, 6]

预期:

0
5
[8]
[8, 6] (list gets appended without affecting the original)

2 个答案:

答案 0 :(得分:0)

类变量应被视为一种全局变量:一个存储整个类的全局状态的位置(很少需要),以及一个定义共享常量的位置(非常常见)。如果您希望实例的数据因实例而异,请在__init__()方法中而不是在类级别进行设置。

就您观察到的差异而言,一种情况是为属性分配值,而另一种情况是对已经存储在属性中的值进行突变。核心问题是分配变异之间的区别。

答案 1 :(得分:0)

做一个任务看起来就解决了,但是我认为还有很多。  对self.list进行赋值时,将创建一个新的单独的实例变量(与数字相同),它是self.list的新引用,并且在删除后,该类将返回其旧列表类变量。因为我们保留了类变量而不是创建实例,所以共享是共享的,这段代码对我很好地解释了:

class test_class:
list = [8]
def addlist(self, liste):
    self.list= [liste]
def appendlist(self,new):
    self.list.append(new)
def delete(self):
    del self.list


object = test_class()

object.addlist(6) ## this creates a new and separate instance variable
print("------")
print(test_class.list)
print(object.list)


object.appendlist(2)  ## adds up to the instance variable
print("------")
print(test_class.list)
print(object.list)

object.delete()    ## deleting the instance var shows that the class var is still there
print("------")
print(test_class.list)
print(object.list)

object.appendlist(3)  ##class variable gets appended to, since we're not asking to create a new one
print("------")
print(test_class.list)
print(object.list)

此打印:

------
[8]
[6]
------
[8]
[6, 2]
------
[8]
[8]
------
[8, 3]
[8, 3]

感谢您的回答!