Skip to main content
 首页 » 编程设计

python之当函数需要成为一个类时

2025年05月04日15duanxz

我正在学习 Python 中 class 的使用。通常我会编写几个函数来运行我的脚本,但最近我正在使用类编写。

对于基本问题,我很抱歉,但是使用类的限制是什么时候?

另一方面,在我的代码中,我编写了这个函数,您可以在其中读取目录中的所有文本文件,并将所有值保存在临时文件中。文本文件为 x、y 和 z 格式。该函数返回临时文件的名称、边界框、原点(左上角)和底部(右下角)。在类中转换这样的函数有用吗?如果是,为什么?如果没有为什么?

import os 
import tempfile 
import glob 
 
class LaserException(Exception): 
    """Laser exception, indicates a laser-related error.""" 
    pass 
 
 
sepType = { 
        "space": ' ', 
        "tab": '\t', 
        "comma": ',', 
        "colon": ':', 
        "semicolon": ';', 
        "hyphen": '-', 
        "dot": '.' 
        } 
 
def tempfile_merge(path,separator,wildcard= '*.txt'): 
    file_temp = tempfile.NamedTemporaryFile(delete=False,dir=path) 
    name = file_temp.name 
    minx = float('+inf') 
    maxx = float('-inf') 
    miny = float('+inf') 
    maxy = float('-inf') 
    for file in glob.glob(os.path.join(path,wildcard)): 
        for line in open(file, "r"): 
            element = line.split(sepType[separator]) 
            if len(element) < 3: 
                raise TypeError("not enough arguments: %s has only %s columns" % (inFile_name_suffix,len(element))) 
            try: 
                maxx = max(maxx, float(element[0])) 
                minx = min(minx, float(element[0])) 
                maxy = max(maxy, float(element[1])) 
                miny = min(miny, float(element[1])) 
            except ValueError: 
                raise LaserException("x,y,z are not float-values") 
            newelement = " ".join([str(e) for e in element])+ "\n" 
            file_temp.write(newelement) 
    file_temp.close() 
    return(name, ((minx,maxy),(maxx,maxy),(maxx,miny),(minx,miny)),(minx,maxy),(maxx,miny)) 

请您参考如下方法:

不要为这个问题感到抱歉。这不是一个愚蠢的问题。这是一个在您学习编程时不断挣扎的问题。

底线是关于如何将工作划分为函数和类的指南,但每个程序员都有自己的看法。你应该找到一些对你有意义的规则并努力遵守它们。但是,请保持开放的心态,并随着你了解更多而适应。

我的建议是,您可以在本网站上四处寻找“何时使用类与函数”的谷歌答案。这是一个很好的:In Python, when should I use a function instead of a method?

希望这对您有所帮助。