[Tutor] self.name vs. passing a name

Che M pine508 at hotmail.com
Tue Jul 28 01:39:25 CEST 2009


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





_________________________________________________________________
NEW mobile Hotmail. Optimized for YOUR phone.  Click here.
http://windowslive.com/Mobile?ocid=TXT_TAGLM_WL_CS_MB_new_hotmail_072009
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090727/072b2365/attachment.htm>


More information about the Tutor mailing list