3

consider the following class

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 output while running the following code is:

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

It's clearly that every time the constructor gets called, the context is not getting maintained instead the array values all seems to get appended into a gloabal variable called arr

I want to know why are the object variables not maintaining the context and leaking into each other?

isnvi23h4
  • 1,910
  • 1
  • 27
  • 45

1 Answers1

2

Because in your code arr is defined as a static member variable in MyClass. In Python these are also called class variables (in contrast to instance variable).

If you want to declare a variable in your class, and you want that variable to be confined to the context of an instance, then you want an instance variable. To do that you need to edit your code a little bit. Remove the class level declaration of arr. and edit init(self) to declare arr as in:

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)))

to read more about instance and class variables check the python documentation:

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

Ouss
  • 2,912
  • 2
  • 25
  • 45
  • 1
    can you post the code to make it into a object varibale? – isnvi23h4 Dec 26 '19 at 12:24
  • Give me 5 minutes to edit this answer! – Ouss Dec 26 '19 at 12:25
  • 1
    but if self.arr needs to be initialised every time on constructor call, then whats the advantage of having a class property! – isnvi23h4 Dec 26 '19 at 12:31
  • There are many uses for "static variables". For example they can be used to count the number of instances of a class. or to share a specific variable among instances of a class where all instances are be able to access it and manipulate it. – Ouss Dec 26 '19 at 12:33
  • 1
    https://docs.python.org/3.8/tutorial/classes.html#class-and-instance-variables – Ouss Dec 26 '19 at 12:42