Search code examples
pythonclassmethodsinstance

Is it possible to update all attributes in class instance by changing just one attribute?


I'd like to update all attributes in my class, if I change at least one attribute, here's my example in Python:

class A:
    def __init__(self, my_list):
        self.my_list = my_list
        self.list_len = len(self.my_list)
    def update_list(self, var1):
        self.my_list.append(var1)

if I create an instance of class A with initial list of 3 elements and call list_len attribute, I get:

a_instance = A([1,2,3])
a_instance.list_len

[Out]: 3

but if I update my_list, the list_len attribute is unchanged, is it possible to update this attribute if my_list is changed without calling update_list_len-like methods?


Solution

  • You can convert the list_len to @property:

    class A:
        def __init__(self, my_list):
            self.my_list = my_list
    
        @property
        def list_len(self):
            return len(self.my_list)
    
    
    a_instance = A([1, 2, 3])
    print(a_instance.list_len)
    
    a_instance.my_list.append(4)
    print(a_instance.list_len)
    

    Prints:

    3
    4