0%

Python之模块导入

这里介绍Python的模块

abstract.png

导入模块中函数

在Python中,一个py源文件即为一个模块。如下所示,有下述两个py文件

figure 1.png

其中,hello.py文件的内容如下所示

1
2
3
4
5
def hello_world():
print("Hello World")

def hello_person(name):
print("Hello",name)

如果我们期望在main.py文件使用hello模块中的函数,可以通过下述手段实现

1
2
3
4
5
6
# 导入hello整个模块
import hello

# 导入整个模块后,可通过 <模块名>.<函数名> 的方式调用函数
hello.hello_world()
hello.hello_person("Aaron")
1
2
3
4
5
6
# 导入hello整个模块,并设置别名为hi,通过模块别名调用函数
import hello as hi

# 通过模块别名调用函数
hi.hello_world()
hi.hello_person("Aaron")
1
2
3
4
5
# 从hello模块导入指定函数, 可直接使用函数名进行函数调用
from hello import hello_world, hello_person

hello_world()
hello_person("Aaron")
1
2
3
4
# 从hello模块导入hello_person函数,并设置别名为hip,可直接使用函数别名进行函数调用
from hello import hello_person as hip

hip("Aaron")
1
2
3
4
5
6
# 导入hello模块中的全部函数,可直接使用函数名进行函数调用
# Note: 不推荐该用法,会导致相同名称的函数发生冲突
from hello import *

hello_world()
hello_person("Aaron")

导入模块中类

现在我们来体现如何导入其他模块定义的类,实现为我所用。有下述两个py文件

figure 2.png

其中,animal.py文件的内容如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Cat:
"""

"""
def __init__(self, name):
self.name = name

def say(self):
print(self.name, "正在喵喵喵")

class Dog:
"""

"""
def __init__(self, name):
self.name = name

def say(self):
print(self.name, "正在狗叫: 汪汪汪")

如果我们期望在main.py文件使用animal模块中的类,可以通过下述手段实现

1
2
3
4
5
6
7
8
# 导入animal整个模块
import animal

# 导入整个模块后,可通过 <模块名>.<类名> 的方式访问类
my_cat1 = animal.Cat("Tom")
my_cat1.say()
my_dog1 = animal.Dog("Lucy")
my_dog1.say()
1
2
3
4
5
6
7
# 导入animal整个模块,并设置别名为an,可通过 <模块别名>.<类名> 的方式访问类
import animal as ani

my_cat2 = ani.Cat("Tom")
my_cat2.say()
my_dog2 = ani.Dog("Lucy")
my_dog2.say()
1
2
3
4
5
6
7
# 从animal模块导入指定类,可直接通过类名访问
from animal import Cat, Dog

my_cat3 = Cat("Tom")
my_cat3.say()
my_dog3 = Dog("Lucy")
my_dog3.say()
1
2
3
4
5
# 从animal模块导入Dog类,并设置类的别名为 doooog,可直接通过类的别名访问
from animal import Dog as doooog

my_dog4 = doooog("Lucy")
my_dog4.say()
1
2
3
4
5
6
7
8
# 导入animal模块中的全部类,可直接通过类名访问
# Note: 不推荐该用法,会导致相同名称的类发生冲突
from animal import *

my_cat5 = Cat("Tom")
my_cat5.say()
my_dog5 = Dog("Lucy")
my_dog5.say()

参考文献

  1. Python编程·第3版:从入门到实践 Eric Matthes著
  2. Python基础教程·第3版 Magnus Lie Hetland著
  3. 流畅的Python·第1版 Luciano Ramalho著
请我喝杯咖啡捏~

欢迎关注我的微信公众号:青灯抽丝