Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | Github | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

1.4. Python 模块

1.4.1. 同级目录

同级目录下有两个文件,分别是 a.py 和 test.py。我们将在 test.py 中导入 a.py

		
a.py
test.py
		
		

a.py 文件

		
neo@MacBook-Pro-Neo ~/workspace/devops % cat a.py 
def say():
    print("hello")%                  		
		
		

test.py 文件

		
neo@MacBook-Pro-Neo ~/workspace/devops % cat test.py 
import a
a.say()		
		
		

运行结果

		
neo@MacBook-Pro-Neo ~/workspace/devops % python3 test.py 
hello		
		
		

1.4.2. 一级目录

		
dir/a.py
dir/__init__.py
test.py
		
		

		
neo@MacBook-Pro-Neo ~/workspace/devops % cat dir/a.py 
def say():
    print("hello")		
    
neo@MacBook-Pro-Neo ~/workspace/devops % cat test.py 
from dir import a
a.say()
		
		

		
neo@MacBook-Pro-Neo ~/workspace/devops % python3 test.py 
hello		
		
		

1.4.3. 二级子目录

		
test.py
dir
  |--subdir
    |-- b.py
		
		
		
		
neo@MacBook-Pro-Neo ~/workspace/devops % cat dir/subdir/b.py 
def sayhello():
    print("helloworld!!!")
    
neo@MacBook-Pro-Neo ~/workspace/devops % cat test.py
from dir.subdir import b 
b.sayhello()% 	
		
		

		
neo@MacBook-Pro-Neo ~/workspace/devops % python3 test.py 
helloworld!!!		
		
		

1.4.4. 子目录调用上级目录

		
neo@MacBook-Pro-Neo ~/workspace/devops % find dir 
dir
dir/a.py
dir/subdir
dir/subdir/c.py
dir/subdir/b.py
		
		
		
neo@MacBook-Pro-Neo ~/workspace/devops % cat dir/subdir/c.py 
import b
b.sayhello()

import sys,os
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(path)
sys.path.insert(0, path)
import a
a.say()

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from dir import a
a.say()		
		
		

		
neo@MacBook-Pro-Neo ~/workspace/devops % python3 dir/subdir/c.py 
helloworld!!!
hello
hello		
		
		

1.4.5. 导入类

		
neo@MacBook-Pro-Neo ~/workspace/devops % cat netkiller/dir/class1.py 
class TestClass():
	def __init__(self, name="None"): 
		self.name = name
	def say(self):
		print(self.name)		
		
		

		
from netkiller.dir.class1 import *
tc = TestClass('neo')
tc.say()