1

I am learning the use of class in Python. Typically I write several function to run my script, but recently i am writing using class.

I am sorry for the basic question, but when is the limit to use a class?

In other hand, inside my code i coded this function where you read all text file in a directory and you save in a temporary file all values. The text files are x,y, and z format. The function returns the name of the temporary file, the bounding box, the origin (top-left corner), and the bottom (bottom-right corner). Is It useful to convert function like this in a class? if yes why? if no why?

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))
Gianni Spear
  • 7,033
  • 22
  • 82
  • 131
  • What do you mean by "but when is the limit to use a class?" ? – Duniyadnd Mar 01 '13 at 16:07
  • I have not clear how much i need to push my coding-style to use the class. I know the answer is the class you need, but I am curious to know the approach to decide to write a class or a function – Gianni Spear Mar 01 '13 at 16:11
  • I think you should post this on http://codereview.stackexchange.com/ for more detailed feedback – YXD Mar 01 '13 at 16:15

2 Answers2

4

Usually you want to use a class when there are multiple common operations you might want to do on a given set of persistent data. In that case it's convenient to bundle the data and the functions that operate on them into a single object.

In your case you could convert this to a function that, in its constructor, reads the files and calculates the values, and then makes them available as attributes of the object. But you're not providing any methods to do anything else with those values, so why bother?

Or you could simply return a collections.namedtuple from your function. This would give you the named-attribute access while also allowing numeric indexing.

I think it's more straightforward as a function returning a namedtuple, but this is largely a matter of the style you prefer.

PS -- I would not expect a function named tempfile_merge to return a bounding box or coordinates. I might humbly suggest a name change.

kindall
  • 178,883
  • 35
  • 278
  • 309
4

Don't be sorry about this question. This not a dumb question. It is a question that is a constant struggle as you learn to program.

The bottom line is that there are guidelines on how to divide up the work into functions vs. classes, but every programmer has their own opinion. You should find some rules that make sense to you and try to stick to them. But, keep an open mind and adapt as you learn more.

What I would suggest is you look around this site for answers to the google of "when to use a class vs. a function". Here is one good one: In Python, when should I use a function instead of a method?

Hope this helps.

Community
  • 1
  • 1
Roger Allen
  • 2,262
  • 17
  • 29