0

I have created a class and created 3 different objects from it. But when I do a change in one of them, other objects get affected too.

I'm running python on pycharm

class Teller():
    def __init__(self,queue=[]):
        self.queue = queue

teller1 = Teller()
teller2 = Teller()
teller1.queue.append(5)
print(teller1.queue)
print(teller2.queue)

I expected the results as [5] and [0] but instead, I get [5] and [5]

  • 2
    Possible duplicate of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Olivier Melançon Aug 14 '19 at 03:48
  • @OlivierMelançon yeah, I have checked that one too, but it was too complicated for me, I didn't understand much. I'm new to python –  Aug 14 '19 at 04:03

2 Answers2

2

When you provide default arguments, it uses the same object every time. So when teller2 is initialized with a default list, it is the same list that teller1 got.

A better way to initialize this would be:

class Teller():
    def __init__(self,queue=None):
        self.queue = queue if queue else list()
RootTwo
  • 4,288
  • 1
  • 11
  • 15
-1

Ths is because both your objects point to the same class tat's initialising the same queue. What I guess you could do is create different classes or call different functions.

Different Functions

class Teller():
    def __init__(self,queue=[]):
        self.queue = queue
    def queue2 (self, queue1=[]):
        self.queue1 = queue1

teller1 = Teller()
teller2 = Teller()
teller1.queue.append(5)
print(teller1.queue)
print(teller2.queue2())

Different Classes

class Teller():
    def __init__(self,queue=[]):
        self.queue = queue

class Teller2():
    def __init__(self, queue = []):
        self.queue = queue

teller1 = Teller()
teller2 = Teller2()
teller1.queue.append(5)
print(teller1.queue)
print(teller2.queue)
Trollsors
  • 492
  • 4
  • 17