避免在Python类中重用慢函数
假设我要创建一个Python类,其中的一个函数输出是其他几个函数所需要的,但这是一个非常缓慢的过程。有没有办法让这个输出成为其他函数使用的属性或全局变量,而不必重新运行slow函数 例如,下面是一个类,其中慢函数由下面两个函数调用: 等级测试(u级):避免在Python类中重用慢函数,python,function,class,attributes,Python,Function,Class,Attributes,假设我要创建一个Python类,其中的一个函数输出是其他几个函数所需要的,但这是一个非常缓慢的过程。有没有办法让这个输出成为其他函数使用的属性或全局变量,而不必重新运行slow函数 例如,下面是一个类,其中慢函数由下面两个函数调用: 等级测试(u级): def __init__(self, A): self.a = A def some_function(self): """ Function to show that the s
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
是说打开一个文件或一个缓慢的卷积过程,那么多次运行它将是一个巨大的时间消耗
如果slow\u函数的输出可以改为一个属性,那么这会有所帮助,但我不知道如何在类的中途完成
任何帮助都将不胜感激 您可以随时在初始化的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
当然只需将输出设置为属性,而不是从methodIn init中返回它,设置self.long\u function\u result=None
。使用任何其他方法时,您可以检查self.long\u function\u result
是否为None。如果是,则调用long函数并更新self.long\u函数\u结果
。如果不是“无”,只需获取值即可。方法不必返回任何内容,您可以使用它们来更新对象的状态。是的,在创建对象之后,最好不要让属性突然出现。它还允许您在对象的任何实例上调用dir
,并查看所有已命名的属性,而无需调用任何方法。@roganjosh如果您有一个对象,而您只希望在调用特定方法后属性才可用,则我可以看到它的用途。不过很少见。
>>> 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