0

I´m currently exploring classes in Python and have a general question on how to update specific attributes of a class.

In my example class I have two Attributes, which will be initialized right at the start and also a class-methode to update one of the two Attributes:

class MyClass:
    def __init__(self, myList):
        self.alpha = myList
        self.beta = myList

    # Method to update a List at specific index
    def update_alpha_list(self, new_value, index):
        self.alpha[index] = new_value

So when I create an Instance of this class and run the method, I figured out, that both of the class-attributes are changed:

# main    

myList = [1, 2, 4]

# Initialize Class Instance
MyClassInstance = MyClass(myList)

print('alpha: {}'.format(MyClassInstance.alpha))        # alpha: [1, 2, 4]
print('beta: {}'.format(MyClassInstance.beta))          # beta:  [1, 2, 4]
print('myList: {}'.format(myList))                      # myList: [1, 2, 4]

# Goal: only update alpha-list
MyClassInstance.update_alpha_list(new_value=3, index=2)

print('alpha: {}'.format(MyClassInstance.alpha))     # alpha: [1, 2, 3]
print('beta: {}'.format(MyClassInstance.beta))       # beta: [1, 2, 3] | Why has value changed
print('myList: {}'.format(myList))                   # myList: [1, 2, 3] | Why has value changed

I can't figure out why this code affects

  • the second class-attribute beta when update_alpha_list() is called
  • the variable myList, which has nothing to do with the class-methode

Could someone explain what is going on in Python when update_alpha_list() is called.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Max
  • 1
  • 1
    Sounds like you could use a [quick guide to how Python objects and variables work](https://nedbatchelder.com/text/names.html). – user2357112 Apr 08 '21 at 14:22
  • Your code only creates one single list. Assignment does not create a copy *of* it, it creates an alias *to* it. – MisterMiyagi Apr 08 '21 at 14:22
  • Because python is pass-by-reference language. For more detail, see https://stackoverflow.com/q/986006/10315163. – Ynjxsjmh Apr 08 '21 at 14:28
  • oh I thought lists behave like variables - good to know thank you very much! link to similiar question: https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-to-prevent-it – Max Apr 08 '21 at 14:36

0 Answers0