python学习:调用其他函数

vim wc.py
 
#!/usr/bin/python
 
def wordCount(s):
    chars = len(s)
    words = len(s.split())
    lines = s.count(' ')
    print lines, words, chars
 
if __name__ == '__main__':
    s = open('/etc/passwd').read()
    wordCount(s)
 
vim 2.py
 
#!/usr/bin/python
 
import wc
 
s = """hello world
python"""
 
wc.wordCount(s)
 
[root@web10 ~]# python 2.py
1 3 18
[root@web10 ~]# python wc.py
24 35 1122
 
既可以调用wc.py, 也可以执行wordCount(s)函数
 
 
 
[root@web10 day04]# touch __init__.py
[root@web10 day04]# ll
total 8
-rw-r--r-- 1 root root  78 May 16 09:36 2.py
-rw-r--r-- 1 root root   0 May 16 10:01 __init__.py
-rw-r--r-- 1 root root   0 May 16 09:40 _init_.py
-rw-r--r-- 1 root root 219 May 16 09:35 wc.py
[root@web10 day04]# cd ..
[root@web10 ~]# ipython
 
In [1]: from day04 import wc
 
In [2]: wc.wordCount('abc')
0 1 3
 
In [3]: import day04.wc
 
In [4]: day04.wc.wordCount('hello world ')
1 2 12
 
 
In [6]: from day04.wc import wordCount
 
In [7]: wordCount('aaa')
0 1 3
 
In [10]: from day04.wc import wordCount as wc
 
In [11]: wc('hello')
0 1 5
 
导入包
原文地址:https://www.cnblogs.com/weifeng1463/p/7519640.html