Share Data Between An External Function And A Python Class Function
Solution 1:
It's a good idea to avoid magic globals, but your report()
function must have some way to know where to look. If it's ok to pass it the object doing the computation, i.e. q
, it can simply print out q.data
. If not, then you can arrange for q
to save its data in the class itself-- obviously this means that the class can only be instantiated once, so I would go with the first option.
Solution 2:
You can't do that unless you instantiate the class somewhere. Currently in your implementation you instantiate the Compute class here:
def externalCompute():
q =Compute()
q.internalCompute()
But as soon as the function finishes q goes out of scope and is destroyed so you will lose all information that the class contains. In order to do what you want to do the Compute class has to be instantiated to not be local to a function (or your function needs to return the instance of the Compute class as to preserve its state.)
Usually you would do that by having one "main" if your python file in this way:
classCompute(object):def__init__(self):
self.data = 0definternalCompute(self):
self.data = 5defexternalCompute(q):
q.internalCompute()
defreport(q):
# access the updated variable self.data from Compute class
data = q.data
print "You entered report"if __name__ == '__main__':
q = Compute()
externalCompute(q)
report(q)
Solution 3:
You actually have access to the data through q.data
, you just have to return it.
Change your code to reflect that fact:
classCompute(object):def__init__(self):
self.data = 0definternalCompute(self):
self.data = 5defexternalCompute():
q = Compute()
q.internalCompute()
return q.data
defreport():
print externalCompute()
report() # 5
If you don't like this approach, you have only a few other options:
- Global variable.
- Instantiating another class.
- Updating the same class you instantiated.
- Database.
- Pickle.
Post a Comment for "Share Data Between An External Function And A Python Class Function"