python模块的函数_Python模块及函数的使用
一.
1.模塊是包含函數(shù)和其他語(yǔ)句的腳本文件,以".py"為后綴名,在Python中可以通過(guò)導(dǎo)入模塊來(lái)使用模塊中的函數(shù)或數(shù)據(jù).
創(chuàng)建一個(gè)文件fun.py內(nèi)容如下:
def f1():
print('hello world!')
def f2(L):
result = 0
for i in L:
result += i
return result
def f3(x):
??? print("old x = " + str(x))
??? x = 0
??? print("change to x = " + str(x))
value=100
再創(chuàng)建另一個(gè)文件shang.py,再在這個(gè)文件調(diào)用fun.py中的函數(shù)
#!/usr/bin/env python
import fun? ? ? ? ? ? ? ? ? //引入模塊
from fun import f1,f2,f3? ? //引入模塊中的函數(shù)
fun.f1()? ? ? ? ? ? ? ? ? ? //與下一個(gè)區(qū)別,用這個(gè)必須先用import引入模塊
f1()
print f2([1,2,3,4,5])
f3(20)
print fun.value? ? ? ? ? ? //打印引入模塊的變量值
結(jié)果如下
hello world!
15
old x = 20
change to x = 0
注:引入fun.py過(guò)程中會(huì)自動(dòng)生成fun.pyc文件并且上述兩個(gè)文件在同一目錄.
2.設(shè)置模塊查找路徑2.
上一例子是在同一目錄
若不在同一目錄,python查找不到,必須進(jìn)行查找路徑的設(shè)置,將模塊所在的文件夾加入系統(tǒng)查找路徑
查看默認(rèn)查找路徑:
import sys
sys.path
添加一個(gè)路徑[將當(dāng)前路徑加入]
import os
import sys
sys.path.append(os.getcwd())
總結(jié)
以上是生活随笔為你收集整理的python模块的函数_Python模块及函数的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 前端怎么导出表格_前端如何导出表格数据
- 下一篇: python练习题实例_Python 练