简介
本文介绍调用模块下的函数。
- 简单展示调用module2中函数。
- 调用module2中函数,其函数同时使用Test_Class中的类。
文件夹结构
每个模块中都必须含有__init__.py文件
各个文件中内容
my_functions文件夹下__init__.py空文件即可。
module2 文件夹下__init__.py
# my_functions/module2/__init__.py
from my_functions.module2.function_c import function_c
from my_functions.module2.function_c import function_e
from my_functions.module2.function_c import function_f
from my_functions.module2.function_d import function_d
module2 下文件function_c.py
# my_functions/module2/function_c.py
from my_functions.module2.function_d import CAdd
from my_functions.Test_Class.test_cal import CCal
def function_c(a, b):
"""计算两个数字的乘积"""
return a * b * 18
def function_e(a, b):
"""计算两个数字的乘积"""
aa = CAdd(a, b)
aa.get_result()
return aa.get_result()
def function_f(a, b):
"""计算两个数字的乘积"""
cc = CCal()
return cc.add(a, b)
pass
module2 下文件function_d.py
# my_functions/module2/function_d.py
def function_d(a, b):
"""计算两个数字的商"""
return a / b
class CAdd:
def __init__(self, a, b):
self.a = a
self.b = b
def get_result(self):
return self.a + self.b
Test_Class 文件夹下__init__.py
from my_functions.Test_Class.test_cal import CCal
Test_Class 文件夹下test_cal.py
class CCal:
def add(self, a, b):
return a + b
def sub(self, a, b):
return a - b
def mul(self, a, b):
return a * b
def div(self, a, b):
return a / b
def pow(self, a, b):
return a ** b
def mod(self, a, b):
return a % b
def sqrt(self, a):
return a ** 0.5
test.py文件
import sys
import os
# 获取当前目录
if getattr(sys, 'frozen', False):
current_dir = os.path.dirname(sys.executable)
else:
current_dir = os.path.dirname(os.path.abspath(__file__))
# 将模块路径添加到系统路径中
sys.path.append(os.path.join(current_dir, 'my_functions'))
def load_function(module_name, function_name):
# 动态加载模块
module = __import__(module_name)
# 获取函数
func = getattr(module, function_name)
return func
params = {"a": 1, "b": 2}
func = load_function('module2', 'function_c')
result = func(**params)
print(result)
params = {"a": 1, "b": 2}
func = load_function('module2', 'function_e')
result = func(**params)
print(result)
params = {"a": 1, "b": 2}
func = load_function('module2', 'function_f')
result = func(**params)
print(result)
params = {"a": 1, "b": 2}
func = load_function('module2', 'function_d')
result = func(**params)
print(result)
结果
36
3
3
0.5
注意:
- 所有的路径都要是绝对路径,不要使用相对路径,否则可能会出现ttempted relative import beyond top-level package错误。
- 一定要将模块路径添加到系统路径中。否则会出现找不到模块的错误。