网络编程
位置:首页>> 网络编程>> Python编程>> 调用其他python脚本文件里面的类和方法过程解析

调用其他python脚本文件里面的类和方法过程解析

作者:He_LiangLiang  发布时间:2021-01-11 13:27:14 

标签:调用,python,脚本,类,方法

这篇文章主要介绍了调用其他python脚本文件里面的类和方法过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

问题描述:

自己编写了若干个Python脚本。

在testC.py里面需要调用testA.py和testB.py里面的若干类和方法。要怎么办?

需要都打包、安装,再去调用吗? 其实不必那么麻烦。

这里有个前提,testA.py, testB.py, testC.py在同级目录下。

如果不在同级目录,后面会补充介绍如何把路径包含过来。


# testA.py
# -*- coding: utf-8 -*-

class testA:
 def testA1():
   print("----testA1")

def testA2(str):
 print("testA2---: " + str)

# testB.py
# -*- coding: utf-8 -*-

def testB():
 print("this is testB")

# testC.py

import logging
from testA import *
from testB import *

logging.basicConfig(level=logging.INFO, filename='mylog.log')
logging.info('Starting program')
# 这个logging仅仅为了掩饰日志记录功能,和这里讨论的主题无关
logging.info("test testA.py")# 调用里面的类
testa = testA
testa.testA1()
# 调用里面的方法
testA2("How are you?")

logging.info("test testB.py")
testB()
logging.info('Ending program')

这里有3个文件(testA.py, testB.py, testC.py)。

在testC.py里面调用另外连个.py脚本的方法就是 import 模块脚本的全部内容。


from testA import *
from testB import *

函数调用语法细节,请参看testC.py里面的代码。

遗留问题:

如果不在当前路径怎么办?

用sys模块,将路径添加进来即可。

例如,我这里就把testA.py放在了当前目录的today文件夹下面。把testB.py放在了父级目录(上一级目录)的yesterday文件夹下面。


import sys
sys.path.append(r'./today')
sys.path.append(r'./../yesterday')
from testA import *
from testB import *

来源:https://www.cnblogs.com/music-liang/p/11863023.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com