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

yipeiwu_com6年前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 *

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python对html过滤处理的方法

如下所示: ##过滤HTML中的标签 #将HTML中标签等信息去掉 #@param htmlstr HTML字符串. def filter_tags(htmlstr): #先过滤C...

Python定义一个跨越多行的字符串的多种方法小结

Python定义一个跨越多行的字符串的多种方法小结

方法一: >>> str1 = '''Le vent se lève, il faut tenter de vivre. 起风了,唯有努力生存。 (纵有疾风起,人...

Python查询IP地址归属完整代码

本文实例为大家分享了Python查询IP地址归属的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*- #...

详解Python 解压缩文件

详解Python 解压缩文件

zipfile模块及相关方法介绍: 1 压缩 1.1 创建zipfile对象 zipfile.ZipFile(file, mode='r', compression=0, allowZi...

python3 图片 4通道转成3通道 1通道转成3通道 图片压缩实例

我就废话不多说了,直接上代码吧! from PIL import Image # 通道转换 def change_image_channels(image, image_path):...