Reputation: 915
Say I were to make a Python class where one of the function outputs is needed for several other functions but is a very slow process. Is there a way to then make this output an attribute or global variable for the rest of the functions to use but not have to rerun the slow function?
For example here is a class where the slow function is called by the next two functions:
class test_class:
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
So it's clear that if slow_function
was say opening a file or a slow convolution process then running it multiple times will be a big time sink.
If the output of slow_function
could instead be made into an attribute then that would help, but I'm not sure how to do this midway through a class.
Any help would be greatly appreciated!
Upvotes: 0
Views: 59
Reputation: 1271
You can assign attributes in an initialised python object at any time.
They don’t have to be done at initialisation, and you can even assign them from outside the object.
>>> 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
EDIT: as per @roganjosh’s comment, you can assign it as none
during initialisation. Not only will you not get AttributeError
s, it’s easier to keep track of all attributes.
>>> 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
Upvotes: 1