In class object, how to auto update attributes?

前端 未结 4 1705
我寻月下人不归
我寻月下人不归 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:51

    if updating one property due to an update on another property is what you're looking for (instead of recomputing the value of the downstream property on access) use property setters:

    class SomeClass(object):
        def __init__(self, n):
            self.list = range(0, n)
    
        @property
        def list(self):
            return self._list
        @list.setter
        def list(self, val):
            self._list = val
            self._listsquare = [x**2 for x in self._list ]
    
        @property
        def listsquare(self):
            return self._listsquare
        @listsquare.setter
        def listsquare(self, val):
            self.list = [int(pow(x, 0.5)) for x in val]
    
    >>> c = SomeClass(5)
    >>> c.listsquare
    [0, 1, 4, 9, 16]
    >>> c.list
    [0, 1, 2, 3, 4]
    >>> c.list = range(0,6)
    >>> c.list
    [0, 1, 2, 3, 4, 5]
    >>> c.listsquare
    [0, 1, 4, 9, 16, 25]
    >>> c.listsquare = [x**2 for x in range(0,10)]
    >>> c.list
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

提交回复
热议问题