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
  • 2
    Possible duplicate of "Least Astonishment" and the Mutable Default Argument Commented Aug 14, 2019 at 3: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 Commented Aug 14, 2019 at 4:03

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.