Skip to main content
 首页 » 编程设计

python之将文件和值作为参数传递给 python 中的函数

2024年10月24日11yyy_WW

我是一个python新手。我正在尝试运行这个简单的 python 示例。我希望将文件和某些值作为参数传递给我的函数 latcalc()。谁能建议我如何将我的文件和值作为参数传递。或者是否有更好的方式/方法来做这些事情。

#!/usr/bin/python 
 
# include the constants 
 
min_length = 1 
max_length = 30 
 
 
# delays 
 
delay = 100 
 
# Speed of light  
 
c_vaccum = 3e8 
 
global filename1 
global filename2 
global filename3 
 
def openfiles(): 
 
    filename1 = open("file1.txt", "w") 
    filename2 = open("file2.txt", "w") 
    filename3 = open("file3.txt", "w") 
 
def latcalc(filename,target_name,vf): 
 
 
    target_name = 0 
 
    for length in range(min_length, max_length): 
            if length < 2: 
                    target_name += (length/(vf * c_vaccum)) 
            elif length == 2: 
                    target_name += delay 
            else: 
                    target_name = target_name 
 
            myline="%s\t%s\n" % (length, target_name) 
            filename.write(myline) 
 
 
openfiles() 
latcalc(filename1,lat40,0.4) 
latcalc(filename2,lat80,0.8) 
latcalc(filename3,lat100,1) 

请您参考如下方法:

我会创建一个小类(给它一个有用的名称)来封装您的数据。 如果您的文件增长,您只需更改您的 create_lats

min_length = 1 
max_length = 30 
 
# delays 
delay = 100 
 
# Speed of light 
c_vaccum = 3e8 
 
#Little class to keep our data in one place  
class Lat: 
    def __init__(self, filename, factor): 
        self.filename = filename 
        self.factor = factor 
        self.file = open(filename, "w") #let the class open the file 
 
 
#now our function needs only one parameter, neat! 
def latcalc(lat): 
    target_name = 0 
 
    for length in range(min_length, max_length): 
        if length < 2: 
            target_name += (length / (lat.factor * c_vaccum)) #acces the class variable 
        elif length == 2: 
            target_name += delay 
        else: 
            target_name = target_name 
 
        myline = "%s\t%s\n" % (length, target_name) 
        lat.file.write(myline) 
 
 
def create_lats(): 
    lats = [] 
    lats.append(Lat("file1.txt", 0.4)) 
    lats.append(Lat("file2.txt", 0.8)) 
    lats.append(Lat("file3.txt", 1)) 
    return lats 
 
 
#loop over your lats created in create_lats 
for lat in create_lats(): 
    latcalc(lat) 
    lat.file.close() #close the file