Storing calculated values in an object

前端 未结 3 1007
谎友^
谎友^ 2020-12-19 17:42

Recently I\'ve been writing a bunch of code like this:

class A:
  def __init__(self, x):
    self.x = x
    self._y = None

  def y(self):
    if self._y is          


        
3条回答
  •  无人及你
    2020-12-19 18:07

    My EAFP pythonista approach is described by the following snippet.

    My classes inherit _reset_attributes from WithAttributes and use it to invalidate the scary values.

    class WithAttributes:
    
        def _reset_attributes(self, attributes):
            assert isinstance(attributes,list)
            for attribute in attributes:
                try:
                    delattr(self, '_' + attribute)
                except:
                    pass
    
    class Square(WithAttributes):
    
        def __init__(self, size):
            self._size = size
    
        @property
        def area(self):
            try:
                return self._area
            except AttributeError:
                self._area = self.size * self.size
                return self._area
    
        @property
        def size(self):
            return self._size
    
        @size.setter
        def size(self, size):
            self._size = size
            self._reset_attributes('area')
    

提交回复
热议问题