Modules are processed with two new statements and one important built-in function we explore here:
import
Lets a client fetch a module as a whole
from
Allows clients to fetch particular names from a module
reload
Provides a way to reload a module's code without stopping Python
Why Use Modules?
Let's start with the obvious first question: why should we care about modules? The short answer is that they provide an easy way to organize components into a system. But from an abstract perspective, modules have at least three roles:
Code reuse
As we saw in Chapter 1, modules let us save code in files permanently.* Unlike code you
type at the Python interactive prompt (which goes away when you exit Python), code in
module files is persistent—it can be reloaded and rerun as many times as needed. More to
the point, modules are a place to define names (called attributes) that may be referenced
by external clients.
System namespace partitioning
Modules are also the highest-level program organization unit in Python. As we'll see,
everything ''lives" in a module; code you execute and some objects you create are always
implicitly enclosed by a module. Because of that, modules are a natural tool for grouping
system components.
Implementing shared services or data
From a functional perspective, modules also come in handy for implementing components
shared across a system, and hence only require a single copy. For instance, if you need to
provide a global data structure that's used by more than one function, you can code it in a
module that's imported by many clients.
Example
''' Created on 2010. 5. 5. @author: all ''' def printer(x): print x # modules attribute
''' Created on 2010. 5. 5. @author: all ''' import modules1 modules1.printer( ' Hello World!')
'''Created on 2010. 5. 5. @author: all ''' #import modules1 #modules1.printer( ' Hello World!') from modules1 import printer printer('Hello World')
'프로그램언어 > python' 카테고리의 다른 글
[Python] 폴더에 존재하는 파일 리스트로 저장. (0) | 2010.06.10 |
---|---|
[Python] Class 구조 갖추기. (0) | 2010.05.09 |
[Python] Class Operator Overloading (0) | 2010.05.02 |
[Python] Why You Will Care: Dictionary Interfaces (0) | 2010.05.01 |
[Python] Built-in Objects Preview (0) | 2010.05.01 |