卖萌的弱渣

I am stupid, I am hungry.

Python: Modules

Python has a way to put definitions in a file and use them in the future.

The python file name is the module name. Within a module, you can access the module by variable __name__.

For example, define fibo.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def fib(n):
    a,b = 0,1
    while b<n:
        print(b, end=' ')   # end define which character to put at the end.
        a,b = b,a+b
    print()

def fib2(n):
    result = []
    a,b = 0,1
    while b<n:
        result.append(b)
        a,b=b,a+b
    return result

In another module or interpreter

1
2
3
4
>>> fibo.fib(1000)
>>> fibo.fib2(100)
>>> fib = fibo.fib
>>> fib(1000)

Import

Importing module will place imported module names in his global symbol table. Use import statement to import a module

1
2
>>> from fibo import fib, fib2    # import two functions from fibo.py
>>> fib(500)

or

1
2
>>> from fibo import *           # import all from fibo.py
>>> fib(500)

Python will not import names begining with underscore _.


Standard Modules

The dir() Function

Find out which names a modules defines.

1
2
>>> import fibo, sys
>>> dir(fibo)

Can also find the names you defines

1
>>> dir()

By default, dir() cannot list built-in functions and variables. You need to specify it

1
2
>>> import builtins
>>> dir (builtins)