Skip to content
Related Articles

Related Articles

Python | Avoiding class data shared among the instances
  • Last Updated : 24 Jan, 2019

Class attributes belong to the class itself and they will be shared by all the instances and hence contains same value of each instance. Such attributes are defined in the class body parts usually at the top, for legibility.

Suppose we have the following code snippet :




# Python code to demonstrate 
# the working of the sharing
# of data variables
  
# Creating a class
class Geek_Class:
    geek = []
  
x = Geek_Class()
y = Geek_Class()
  
# Apending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
  
# Printing the values for x and y 
print(x.geek)
print(y.geek) 
Output:
[1, 2, 3, 4]
[1, 2, 3, 4]

It prints [1, 2, 3, 4] for x and [1, 2, 3, 4] for y. Suppose the output we want is [1, 3] for x and [2, 4] for y. We can get the desired output by the following ways:

Method #1: By declaring them inside the __init__



Declaring the variables inside the class declaration makes them class members and not instance members. Declaring them inside the __init__ method ensures that a new instance of the members is created alongside every new instance of the object, which is what we need.




# Python code to demonstrate 
# the working of the sharing
# of data variables
  
# Creating a class inside __init__
class Geek_Class:
    def __init__(self):
        self.geek = []
  
x = Geek_Class()
y = Geek_Class()
  
# Apending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
  
# Printing the values for x and y 
print(x.geek)
print(y.geek) 
Output:
[1, 3]
[2, 4]

In the original code no value is assigned to list attribute after instantiation; so it remains a class attribute. Defining list inside __init__ works because __init__ is called after instantiation.
 

Method #2: By creating the new list and storing the values in that.




# Python code to demonstrate 
# the working of the sharing
# of data variables
  
# Creating a class 
class Geek_Class:
    geek =[]
  
x = Geek_Class()
y = Geek_Class()
  
# Creating the new lists
x.geek = []
y.geek = []
  
# Apending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
  
# Printing the values for x and y 
print(x.geek)
print(y.geek) 
Output:
[1, 3]
[2, 4]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :