Dynamically update attributes of an object that depend on the state of other attributes of same object

后端 未结 2 1360
闹比i
闹比i 2021-02-02 01:40

Say I have an class that looks like this:

class Test(object):
   def __init__(self, a, b):
      self.a = a
      self.b = b
      self.c = self.a + self.b 
         


        
2条回答
  •  别那么骄傲
    2021-02-02 02:10

    The simplest solution is to make c a read-only property:

    class Test(object):
    
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        @property
        def c(self):
            return self.a + self.b
    

    Now every time you access test_instance.c, it calls the property getter and calculates the appropriate value from the other attributes. In use:

    >>> t = Test(2, 4)
    >>> t.c
    6
    >>> t.a = 3
    >>> t.c
    7
    

    Note that this means that you cannot set c directly:

    >>> t.c = 6
    
    Traceback (most recent call last):
      File "", line 1, in 
        t.c = 6
    AttributeError: can't set attribute
    

提交回复
热议问题