类方法只需要执行一次时如何避免重复调用

问题描述 投票:0回答:2

下面是一个片段,其中我有很长的计算,我只想执行一次 - 因为它需要很长时间。我需要在其他方法中重复调用此计算(在本示例中,只有一个 -

do_something_with_my_value
)。

有没有办法让

my_value
只执行一次,并将值存储下来以便在
do_something_with_my_value
中使用它?

我可以通过手动设置类属性来将

my_value
的返回值绑定到函数本身中。但这需要类型提示返回
None

from typing import List


class Example:
    def __init__(self) -> None:
        pass

    def my_value(self) -> int:
        """Lenghthy calcultion, and so don't want to put in __init__"""
        return 1

    def do_something_with_my_value(self) -> List[int]:
        """Repeatedly uses my_value."""
        return [x + self.my_value() for x in range(1, 1000)]

我想知道是否有一种“Pythonic”设计可以避免像上面的代码片段那样重复进行冗长的计算。

非常感谢您的帮助。

python performance class oop
2个回答
1
投票

my_value
可能应该是一个可以跟踪计算何时以及是否进行的属性。

class Example:
    def __init__(self):
        self._actual_value: Optional[int] = None

    @property
    def my_value(self) -> int:
        if self._actual_value is None:
            self._actual_value = 1

        return self._actual_value

    def do_something_with_my_value(self) -> list[int]:
        return [x + self.my_value for x in range(1, 1000)]

当从

self._actual_value
的 getter 返回其值时,大多数类型检查器应该能够将
int
的类型缩小为
my_value


0
投票

如果 my_value 在类的整个生命周期中永远不会改变,那么来自 functoolscached_property 装饰器是理想的

from functools import cached_property

class Example:

    @cached_property
    def my_value(self) -> int:
        """Lengthy calculation goes here"""
        return 1

    def do_something_with_my_value(self) -> list[int]:
        """Note how my_value is accessed as a property rather than a function call"""
        return [x + self.my_value for x in range(1, 1000)]
© www.soinside.com 2019 - 2024. All rights reserved.