Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python为什么对象属性彼此泄漏_Python_Python 3.x_Class_Object_Constructor - Fatal编程技术网

python为什么对象属性彼此泄漏

python为什么对象属性彼此泄漏,python,python-3.x,class,object,constructor,Python,Python 3.x,Class,Object,Constructor,考虑下面的类 import random class MyClass(): arr = [] def __init__(self, size): for index in range(size): self.arr.append(random.random()) print("the size of the array is : " + str(len(self.arr))) MyClass(4) MyClass(

考虑下面的类

import random

class MyClass():
    arr = []

    def __init__(self, size):
        for index in range(size):
            self.arr.append(random.random())

        print("the size of the array is : " + str(len(self.arr)))


MyClass(4)
MyClass(3)
MyClass(2)
MyClass(1)
运行以下代码时的输出为:

the size of the array is : 4
the size of the array is : 7
the size of the array is : 9
the size of the array is : 10
很明显,每次调用构造函数时,上下文都不会得到维护 相反,数组值似乎全部附加到一个名为
arr


我想知道为什么对象变量不维护上下文并相互泄漏?

因为在您的代码中,
arr
被定义为
MyClass
中的静态成员变量。在Python中,这些变量也称为类变量(与实例变量不同)

如果您希望在类中声明一个变量,并且希望该变量被限制在实例的上下文中,那么您需要一个实例变量。要做到这一点,您需要稍微编辑一下代码。删除
arr
的类级声明。并编辑init(self)以声明
arr
,如下所示:

class MyClass():
    def __init__(self, size):
        self.arr = []
        for index in range(size):
            self.arr.append(random.random())

        print("the size of the array is : " + str(len(self.arr)))
要了解有关实例和类变量的更多信息,请查看python文档:


你能把代码发布成一个对象变量吗?给我5分钟来编辑这个答案!但是如果每次调用构造函数时都需要初始化self.arr,那么拥有类属性有什么好处呢!“静态变量”有很多用途。例如,它们可以用来计算类的实例数。或者在一个类的实例之间共享一个特定变量,所有实例都可以访问和操作该变量。