If I have a function:
def foo(self, a, b):
c = a + b
return c
How can I call foo without changing c in the function? So let's say I call foo in another function:
def bar(self):
z = self.foo(2, 4)
return (z)
and then I want to call foo again in a separate function, but I want c from the time 'bar' was called.
def baz(self):
self.foo(?, ?) # trying to just get c, without any changes.
Basically, i'm trying to keep an account in class such that other classes can have access to the same account; just a simple balance, adding and subtracting money.
Thanks.
why not store the result in
self
, and have optional arguments to see if it should to any calculations?Something like:
Now if you call
foo
with arguments, it will add all arguments and store it. If called with no arguments it will return the last stored value.I've taken what Rohan provided for an answer and come up with the following. It seems to work, although there may be a better/preferred way to accomplish this.
The following code allows me to keep track an account balance across multiple classes and methods.
c
is local to the function and not static. That means that every time the function exits,c
gets garbage collected. Why don't you just store the value ofc
as computed the first time? It seems like the obvious answer.Store
c
as class variable or global and override the function to return old value.e.g.
Note: you will have to handle when to update
stored_c
and any concurrency issues.Update: WRT glglgl's comment, updated for method overloading.
You'll need to have some construct to save the last result. E.g., you can do some wrapper to the function which does
This is a so-called "decorator function".
Now if you do
the function
foo
(itself, not its result!) is used as an argument forkeep_result()
which creates a new functionwrapper()
which calls the original function, saves its result into an attribute and returns the result. This new function is returned in place of the original functionfoo()
.So you can say
and then do
and you get the same.
It seems like the thing you want is a cached property. You can make a decorator implementing descriptor that does that for you as a generic thing to use in future:
Let's look at the example:
Here are some tests.