Python Module

来源:互联网 发布:淘宝粉丝福利购卖家 编辑:程序博客网 时间:2024/04/29 18:51

1 如何实现一个module:

简单的说写个函数保存为xx.py 然后再另一个py文件中import就可以了。

import的语法为:

import module1[, module2[,... moduleN]

A module is loaded only once, regardless of the number of times it is
imported. This prevents the module execution from happening over and
over again if multiple imports
occur.

2 from xx import XX

Syntax:

from modname import name1[, name2[, ... nameN]]

Example:

For example, to import the function fibonacci from the module fib, use the following statement:

from fib import fibonacci


3.python 搜索module的方法:
  • The current directory.

  • If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.

  • If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

4.

The dir( ) Function:

The dir() built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables, and functions that are defined in a module.

Example:

#!/usr/bin/python

# Import built-in module math
import math

content = dir(math)

print content;

This would produce following result:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']

Here the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

The globals() and locals() Functions:

The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locally from that function.

If globals() is called from within a function, it will return all the names that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

The reload() Function:

When the module is imported into a script, the code in the top-level portion of a module is executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function importsa previously imported module again.

Syntax:

The syntax of the reload() function is this:

reload(module_name)

Here module_name is the name of the module you want to reload and not the string containing the module name. For example to re-load hello module, do the following:

reload(hello)


原创粉丝点击