计算属性(如果不存在)

dav*_*345 6 python

我试图访问不应该在__init__我的类的方法中创建的属性,但可以通过调用另一个方法来计算.我试图这样做,如果我尝试访问该属性,它不存在,它将自动计算.但是,如果属性确实存在,即使值不同,我也不希望重新计算它.例如:

class SampleObject(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def calculate_total(self):
        self.total = self.a + self.b

sample = SampleObject(1, 2)
print sample.total   # should print 3
sample.a = 2
print sample.total   # should print 3
sample.calculate_total()
print sample.total   # should print 4
Run Code Online (Sandbox Code Playgroud)

到目前为止,我最好的解决方案是创建一个get_total()方法来完成我需要的工作.

class SampleObject2(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def calculate_total(self):
        self.total = self.a + self.b

    def get_total(self):
        if hasattr(self, 'total'):
            return self.total
        else:
            self.calculate_total()
            return self.total

sample2 = SampleObject2(1, 2)
print sample2.get_total() # prints 3
sample2.a = 2
print sample2.get_total() # prints 3
sample2.calculate_total()
print sample2.get_total() # prints 4
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我已经知道在python中使用getter是不受欢迎的,我希望每次我想访问该属性时都避免调用此函数.这是我最好的解决方案,还是有更清洁,更pythonic的方式来做到这一点?

这是我编写的一个例子.在我的实际问题中,calculate_total()是一个耗时的过程,不一定需要调用.所以我不想在init方法中执行它.

agh*_*ast 10

你想使用@property装饰器.创建一个方法,它将像普通属性一样访问,执行延迟计算:

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
Run Code Online (Sandbox Code Playgroud)