Is it possible to write a function such that in every call it save data; for example- the following function takes two arguments x & y; where x is a data and y is the array size. Call the function first time, it would create y dimensional array, fill the first position with x value and in the second call it would fill the 2nd position of the array and continue and it will return a average when at least 2 values are in that array. The array size would be fixed, if call the function more than y times, it will delete first data (FIFO).
def storedata(x,y):
return z
CodePudding user response:
you can use global variables to keep your data in them and call them between your functions.
check out this page: What is the pythonic way of saving data between function calls? maybe solve your problem if you want to use the class and attribute solution.
CodePudding user response:
You should use a class when you want to store data.
An small example is given below, but please look online for tutorial and examples to fully understand the working of classes and OOP in python.
class Storedata:
def __init__(self, x, y):
self.arr = []
self.max_arr_size = y
self.add_data(x)
def add_data(self, x):
if len(self.arr) < self.max_arr_size:
self.arr.append(x)
def __call__(self):
return sum(self.arr)/len(self.arr)
storedata = Storedata(3, 5)
print(storedata.arr)
>>> [3]
print( storedata() )
>>> 3.0
storedata.add_data(5)
print( storedata() )
>>> 4.0
