假设有两个文件file1.py,file4.py。file4.py文件需要调用file1.py文件中的某个变量。
file4.py与file1.py之间是通过文件中的函数相关联的,其中file1.py需要经过三个文件file2.py,file3.py,file4.py之间的相互关系才能到达file4.py。
原代码是
file1:
class LabanWidget(BVHPlayerPy):
def loadFile(self):
str=cal.Calculation(filePath[0])
generate(str)
self.FlodPanel.Paint()
file2:
def Paint(self):
self.Arm_H.plot()
file3:
def plot(self):
timer.timeout.connect(self.update_H)
def update_H(self):
read_Mdl().read()
file4:
def read(self):
'''读表格,获得数据'''
ExcelFile = xlrd.open_workbook('MDL.xls', formatting_info=True)
此处的代码逻辑是想要把file4中的MDL.xls换成参数,可以随导入的文件名称变化,file1中的变量str中存储了导入的文件名称,现在不想通过传参的形式来改变,因为中间经过的文件太多,识别不了。
解决思路是讲str设置为全局变量,在file1中的方法改变该变量之后,由file4导入file1,并调用该参数。
1。首先需要做的是先在file1中的类内部,函数外部给str赋初始值
2.在函数内部用global声明str
3.file4导入file1,调用file1的变量str
修改后的代码为:
file1:
class LabanWidget(BVHPlayerPy):
str='jack'#赋初始值
def loadFile(self):
global str #声明全局变量
str=cal.Calculation(filePath[0])
generate(str)
self.FlodPanel.Paint()
file4:
import LabanWidget #导入待传参的文件
class read_Mdl():
def read(self):
str1=LabanWidget.str #调用待传参文件的变量
ExcelFile = xlrd.open_workbook(str1+'.xls', formatting_info=True)