私はでの使用法を学んでいclass
ますPython
。通常function
、スクリプトを実行するためにいくつか作成しますが、最近はクラスを使用して作成しています。
基本的な質問で申し訳ありませんが、クラスの使用制限はいつですか?
一方、私のコード内では、ディレクトリ内のすべてのテキストファイルを読み取り、すべての値を一時ファイルに保存するこの関数をコーディングしました。テキストファイルは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))