调用Python脚本指定函数

简介

本文介绍调用模块下的函数。

  1. 简单展示调用module2中函数。
  2. 调用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

注意:

  1. 所有的路径都要是绝对路径,不要使用相对路径,否则可能会出现ttempted relative import beyond top-level package错误。
  2. 一定要将模块路径添加到系统路径中。否则会出现找不到模块的错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值