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.