代码之家  ›  专栏  ›  技术社区  ›  isnvi23h4

python为什么对象属性会互相泄漏[duplicate]

  •  1
  • isnvi23h4  · 技术社区  · 5 年前

    考虑下面的课程

    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
    

    很明显,每次调用构造函数时,上下文都没有得到维护 相反,数组值似乎都被附加到一个名为gloabal的gloabal变量中 arr

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

    2 回复  |  直到 5 年前
        1
  •  1
  •   Ouss    5 年前

    因为在你的代码里 arr 定义为 静止的 中的成员变量 MyClass . 在Python中,这些 类变量 (与实例变量相反)。

    如果要在类中声明一个变量,并且希望该变量被限制在实例的上下文中,则需要 实例变量 . 为此,您需要稍微编辑一下代码。删除的类级声明 阿里尔 . 编辑 初始化 (自己)宣布 阿里尔 例如:

    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文档:

    https://docs.python.org/3.8/tutorial/classes.html#class-and-instance-variables