随笔-76  评论-359  文章-1  trackbacks-0
文件fib.py,内容如下

def fib1(n):
    a, b = 0, 1
    while b < n:
        print b
        a, b = b, a+b

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

导入module,有两种方法:
1,
>>> import fib
>>> fib.fib1(1000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fib1(1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'fib1' is not defined

2,
>>> from fib import fib1, fib2   #或者 from fib import *
>>> fib
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'fib' is not defined
>>> fib1(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fib1
<function fib1 at 0x00B35630>

可见区别是:方法一只导入了模块名,方法二只导入了模块中的函数名。

dir()

    The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:

>>> import fib, sys
>>> dir(fib)
['__name__', 'fib1', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']

    dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__:

>>> import __builtin__
>>> dir(__builtin__)
posted on 2006-10-11 10:23 一直最用心,永远最好听 阅读(102) 评论(0)  编辑  收藏 所属分类: 计算机&网络

标题  
姓名  
主页
验证码 *  
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交