12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

• Coupling: avoid changing variables in another module file directly. We introducedthis concept in the prior chapter, and we’ll revisit it in the next part of thebook when we focus on modules. For reference, though, remember that changingvariables across file boundaries sets up a coupling between modules similarto how global variables couple functions—the modules become difficult tounderstand and reuse. Use accessor functions whenever possible, instead ofdirect assignment statements.Figure 17-1 summarizes the ways functions can talk to the outside world; inputs maycome from items on the left side, and results may be sent out in any of the forms onthe right. Many function designers prefer to use only arguments for inputs, andreturn statements for outputs.InputsArgumentsGlobal variablesFiles/streamsFunctionLocal variablesOutputsReturn statementMutable argumentsGlobal variablesFiles/streamsOther functionsFigure 17-1. Function execution environment. Functions may obtain input and produce output in avariety of ways, though functions are usually easier to understand and maintain if you use argumentsfor input, and return statements and anticipated mutable argument changes for output.Of course, there are plenty of exceptions to the preceding design rules, includingsome related to <strong>Python</strong>’s OOP support. As you’ll see in Part VI, <strong>Python</strong> classesdepend on changing a passed-in mutable object—class functions set attributes of anautomatically passed-in argument called self to change per-object state information(e.g., self.name='bob'). Moreover, if classes are not used, global variables are oftenthe best way for functions in modules to retain state between calls. The side effectsaren’t dangerous if they’re expected.Functions Are Objects: Indirect CallsBecause <strong>Python</strong> functions are objects at runtime, you can write programs that processthem generically. Function objects can be assigned, passed to other functions,stored in data structures, and so on, as if they were simple numbers or strings. We’ve370 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!