[英]How can I call a method in one file that uses a data structure that has been changed by another file?
I wanted to call a method in one file that picks a random number from a list of numbers with a length defined by another file. 我想在一个文件中调用一个方法,该方法从由另一个文件定义的长度的数字列表中选择一个随机数。
Here's what I currently have: 这是我目前拥有的:
#file1
import file2
class Creator(object):
def make_shape():
return Shape(len(file2.sideList)) #takes a parameter of sides
shape = Creator.make_shape() #gets called after sideList is given a certain sequence
#file2
import random
sideList = []
for i in range(1, random.randint(1, 10)):
sideList.append(i)
The obvious problem with the code above is that when file2 is imported, sideList is imported as [] instead of [1, 2, 3, etc]. 上面的代码的明显问题是,当导入file2时,sideList作为[]而不是[1、2、3等]导入。 So when the make_shape() method is called, the shape returned would be a shape with 0 sides. 因此,当调用make_shape()方法时,返回的形状将是带有0个边的形状。
So how could I "update" sideList in file2 so that I could call the make_shape() method using an "updated" version of file2.sideList? 那么,如何才能“更新” file2中的sideList,以便可以使用file2.sideList的“更新”版本来调用make_shape()方法?
Could you create a function in file 2 that accommodates your needs? 您能否在文件2中创建一个满足您需要的功能?
#file1.py
import file2
class Creator(object):
def make_shape():
return Shape(len(file2.sideList())) #takes a parameter of sides
shape = Creator.make_shape() #gets called after sideList is given a certain sequence
#file2.py
import random
def sideList():
ret = []
for i in range(1, random.randint(1, 10)):
ret.append(i)
return(ret)
Edit: 编辑:
#file2.py
import random
def sideList():
dataTarget = "__Data__.csv"
if os.path.isfile(dataTarget):
fh = open(dataTarget)
ret = fh.read().split("\n")
else:
ret = []
for i in range(1, random.randint(1, 10)):
ret.append(i)
fh = open(dataTarget)
fh.write(ret.join(\n))
fh.close()
return(ret)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.