Calculate attribute if it doesn't exist

后端 未结 2 1981
忘掉有多难
忘掉有多难 2020-12-16 04:18

I am trying to access an attribute that shouldn\'t be created in the __init__ method of my class but can be calculated by calling another method. I am trying to

2条回答
  •  不知归路
    2020-12-16 04:43

    You want to use the @property decorator. Create a method, that will be accessed like a normal attribute, that does lazy computation:

    class SampleObject:
    
        def __init__(self):
            # ...
            self._total = None
    
        @property
        def total(self):
            """Compute or return the _total attribute."""
            if self._total is None:
                self.compute_total()
    
            return self._total
    

提交回复
热议问题