代码之家  ›  专栏  ›  技术社区  ›  user8188120

避免在Python类中重用慢函数

  •  0
  • user8188120  · 技术社区  · 5 年前

    假设我要创建一个Python类,其中一个函数输出对于其他几个函数是必需的,但却是一个非常缓慢的过程。有没有办法让这个输出成为其他函数使用的属性或全局变量,而不必重新运行慢速函数?

    例如,这里有一个类,在这个类中,下面两个函数调用慢函数:

    等级测试:

        def __init__(self, A):
                self.a = A
    
        def some_function(self):
                """ Function to show that the slow function feeds of another function first """
                a = self.a
                a*=2
                return a
    
        def slow_function(self): 
                """ Imagine this is a very slow function """
                test_value = self.some_function()
                test_value*=2
                return test_value
    
        def using_slow_function(self): 
                """ Calls the very slow function and then operates on the output """
                b = self.slow_function()
                b *=2
                return b
    
        def using_slow_function_again(self):
                """ Calls the very slow function and then operates on the output """
                c = self.slow_function()
                c *= 2
                return c
    

    很明显如果 slow_function 据说打开一个文件或一个缓慢的卷积过程,然后运行它多次将是一个大的时间接收器。

    如果 慢速功能 但是我不知道如何在一个类的中途完成。

    1 回复  |  直到 5 年前
        1
  •  1
  •   dijksterhuis    5 年前

    可以随时在初始化的python对象中分配属性。

    它们不必在初始化时完成,您甚至可以从对象外部分配它们。

    >>> class A:
    ...     def __init__(self):
    ...         self.a = 1
    ...     def thing(self):
    ...         self.b = 2
    ... 
    >>> c=A()
    >>> c.a
    1
    >>> c.b
    Traceback (most recent call last):
      module __main__ line 141
    traceback.print_exc()
      module <module> line 1
    c.b
    AttributeError: 'A' object has no attribute 'b'
    >>> c.thing()
    >>> c.b
    2
    >>> c.c = 3
    >>> c.c
    3
    

    编辑:根据@roganjosh的评论,您可以将其指定为 none 在初始化过程中。你不仅得不到 AttributeError

    >>> class A:
    ...     def __init__(self):
    ...         self.a = 1
    ...         self.b = None
    ...     def thing(self):
    ...         if self.b is None:
    ...             self.b = 2
    ... 
    >>> c=A()
    >>> c.b
    None
    >>> c.thing()
    >>> c.b
    2
    >>> c.b = 3
    >>> c.thing()
    >>> c.b
    3