Che M wrote:
This is another very basic structural question, related to one I asked last 
week, and again is not necessarily germane only to Python.

Let's say you have a sequence of two calculations or manipulations you need to do, each 
one done as a function called by an overall calculate_something() function.  The 
"answer" to each function is then used in the next function.  I can think of 
two ways to make that answer available for use in the next function:  1) pass it in, or 
2) declare it as self.answer and then it is available to the whole class instance.

What are the dis/advantages to these two different ways?  Here are examples, 
with only the overall calculate_something() function shown:

1.Pass the variable to the second function.

def calculate_something(self):
    answer = self.do_first_calculation()    #1st function returns answer
    self.do_second_calculation(answer)    #2nd is passed answer and uses it.

2. Create the variable in the class instance scope and use that in the second 
function.

def calculate_something(self):

    self.do_first_calculation()                 #1st function creates 
self.answer

    self.do_second_calculation()             #2nd uses self.answer

Both of these approaches can work, but I would like to better understand when 
it is best to do one or the other.  Obviously if I know I will need to make 
self.answer available for use by other functions, I would want to choose (2).  
But what other considerations should I, well, consider?

Thanks,
Che


You call these functions, but since you have the "self" argument, I'll assume it's a method instead.

use #2 only if the "answer" is relevant for further operations, AND (is time-consuming to calculate compared to the memory consumed by storing it, OR if calculating it has side effects)

prefer #1 because:
     it doesn't take up space in the object
it goes away when the particular method ends, not when the object is destroyed (rule -- the sooner the better)
     it doesn't clutter the namespace of the class

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to