In class object, how to auto update attributes?

前端 未结 4 1707
我寻月下人不归
我寻月下人不归 2020-12-03 00:12

I have a class which has multiple attributes that are related, for example:

class SomeClass:
    def __init__(self, n=0):
        self.list = range(n)
               


        
4条回答
  •  天涯浪人
    2020-12-03 00:35

    Ignacio's @property solution is great but it recalculates the list every time you reference listsquare - that could get expensive. Mathew's solution is great, but now you have function calls. You can combine these with the 'property' function. Here I define a getter and a setter for my_list (I just couldn't call it 'list'!) that generates listsquare:

    class SomeClass(object):
    
        def __init__(self, n=5):
            self.my_list = range(n)
    
        def get_my_list(self):
            return self._my_list
    
        def set_my_list(self, val):
            self._my_list = val
            # generate listsquare when my_list is updated
            self.my_listsquare = [x**2 for x in self._my_list]
    
        # now my_list can be used as a variable
        my_list = property(get_my_list, set_my_list, None, 'this list is squared')
    
    x = SomeClass(3)
    print x.my_list, x.my_listsquare
    x.my_list = range(10)
    print x.my_list, x.my_listsquare
    

    This outputs:

    [0, 1, 2] [0, 1, 4]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    

提交回复
热议问题