-1

This was very strange and kind of frustrating. So I have a class with default argument constructor.

class part:
  def __init__(self, num, center=[0, 0, 0]):
    self.center = center
    self.center[1] = num

a = part(1)
print(a.center)
b = part(2)
print(a.center)
print(b.center)

if I run my code above, I got

[0, 1, 0]
[0, 2, 0]
[0, 2, 0]

Which is not what I really want.

I have found the solution which I have answered underneath. However, I wonder why is Python designed like this which is very confusing.

DrKeith
  • 59
  • 5

1 Answers1

0

The solution is to pass arguments to default constructors.

class part:
  def __init__(self, num, center=[0, 0, 0]):
    self.center = center
    self.center[1] = num

a = part(1, [0,0,0])
print(a.center)
b = part(2, [0,0,0])
print(a.center)
print(b.center)

which outputs

[0, 1, 0]
[0, 1, 0]
[0, 2, 0]
DrKeith
  • 59
  • 5