1

I am new to Python and I am trying to understand why the values of one instance variable, that is supposed to be specific for the object created, are passing to other objects of the same class.

An example of my code is:

class Car(object):
def __init__(self, engine=[]):
    self.engine = engine

def add_engine(self, num):
    self.engine.append(num)

car1 = Car()
car1.add_engine(2)

car2 = Car()
car2.add_engine(6)

print(car1.engine) # Outputs [2,6]
print(car2.engine) # Outputs also [2,6]

As I understand, engine should be an instance attribute, why does it behave like a class object attribute in this example?

Thank you very much!

Thanos Dim
  • 11
  • 2

0 Answers0