库函数调用
python导入模块有如下几种写法:以matplotlib为例
1、import matplotlib
2、from matplotlib import *
3、from matplotlib import pylot
4、matplotlib.pylot as plt
以上4种方法中建议第4种。首先要知道matplotlib只是一个目录名称,而该目录下有许多xxx.py文件,每个文件中可能有多个库函数。第一种方法如果需要从matplotlib中使用其下的函数,如调用pyplot(对应pylot.py文件)中的figure()函数,则需要写成matplotlib.pyplot.figure(),名称太长,比较麻烦;而第二种不建议使用,因为*表示导入了matplotlib中的所有.py文件及文件中的函数,这样虽然使用pyplot的时候直接写成pyplot可以简写,但是如果matplotlib下的函数有函数名和其他定义的函数名相同的时候就会冲突导致报错;当然第4种是最好的,既可以简写也不会冲突,使用pyplot中figure函数则可以直接写成plt.figure()
自定义函数调用
python导入模块有如下几种写法:以matplotlib为例
A、函数调用
假设已经编写好了一个hello.py模块,内容为定义的一个函数:
def Hello():
print('Hello world')
当前新建一个文件run.p,其中调用了hello模块,内容为:
import hello
h = hello.Hello()
记住Hello后有括号,当运行run.py文件,得到结果如下:
Hello world
以上为导入自定义模块的方法。
B、类调用
如果将上面的hello.py改为:
def Hello():
print('Hello world')
def greeting():
print('how are you')
将run.py写为
import hello
hello = hello.Hello()
greet = hello.greeting()
运行会报错:
AttributeError: 'NoneType' object has no attribute 'greeting'
此时我们需要将hello.py文件改为类,如下:
class Speak():
def Hello():
print('Hello world')
def greeting():
print('how are you')
调用的时候run.py为:
import hello
h = hello.Speak
hello = h.Hello()
greet = h.greeting()
C、路径问题-(相对路径)
以上自定义模块的调用是假设自定义hello.py模块和当前程序run.py在用一个文件夹下,如果hello.py是在当前路径下的一个子目录test1中,则只要将run.py改为:
from test1 import hello
'''
or
import test1.hello as th #因为hello.py是位于test1文件夹下的,如果test1是文件
test.py, 而hello是test1.py下的类或函数则不能这么调用
h = th.Speak
'''
h = hello.Speak
hello = h.Hello()
greet = h.greeting()
上面代码中说的解释的那部分很关键,再次强调一下:
import matplotlib.pyplot as plt是因为matplotlib是一个文件夹,而pyplot是一个.py文件,所以可以直接用matplotlib.pyplot来调用,如果matplotlib是一个.py文件,而pyplot是它下面的一个函数或者类,则不能直接用点来调用,而要用
from matplotlib import pyplot
or
import matplotlib as pl
plt = matplotlib.pyplot()
D 、路径问题--(绝对路径)
以下1,2都是使用绝对路径
总结:
import sys
sys.path.append('..') #表示导入当前文件的上层目录到搜索路径中
sys.path.append('/home/xxx') # 绝对路径
import os
sys.path.append(os.getcwd()) # 获取当前工作路径
#(注意:当前工作路径不一定是正在编辑的程序对应的路径)
#另外可以使用insert,这里不细说
sys.path.insert(1, "./xxx")
此时借助python内置函数sys放置路径
将run.py改为:(实际上sys里面的路径不需要写那么长,见part three)
import sys
sys.path.append('D:/software/python/note/testpy1/test1')
import hello
h = hello.Speak
hello = h.Hello()
greet = h.greeting()
例如导入上级模块,则只需要将上级模块的路径写出来,所以sys.path的作用是:当使用import语句导入模块时,解释器会搜索当前模块所在目录以及sys.path指定的路径去找需要import的模块,因此可以直接把上级目录加到sys.path里:sys.path.append(’…/’)
“这个方法原理就是利用了系统变量,python会扫描path变量的路径来导入模块”.在$python\Lib\site-packages目录下新建一个.pth的文件,如module_hello.pth,里面写上hello.py的路径,如:
D:\software\python\note\testpy1\test1
这个时候需要加载path,所以需要将run.py, hello.py以及IDLE编译器都重新打开,这个时候run.py只要写如下:
import hello
h = hello.Speak
hello = h.Hello()
greet = h.greeting()
补充:通常定义一个类我们需要初始化__init__,否则找不到属性(为空),这里只是简单的print(),不需要用到类的属性,可以查看文献为什么要用__init__:https://blog.csdn.net/geerniya/article/details/77487941