0

I'm doing a python project where I got a tons of very different functions. I want to somehow organize them together for the future usage, and, of course, for the easier debugging.

However, is it good habit to arrange lots of functions in a class so that they would be attributes, or just put them all in a file?

A related post could be found here: Differences between `class` and `def` where the author specifically indicated that "class is used to define a class (a template from which you can instantiate objects)", so it seemed like functions, methods to change the objects, might not be used as class.

But the official python documentation stated that "Classes provide a means of bundling data and functionality together." So arranging a bunch of functions in a class seemed to be a suggested habit.

A attempt example was achieved as following

class class1(object):
    """description of class"""

    def fun1(x,y):
        return x**2+y**2

where

class1.fun1(1,2)

returned the result 5. As shown, the function fun1 was now better organized, and one could easily find where it was and debug it.

However, one could simply import the function fun1 from a file as

def fun1(x,y):
    return x**2+y**2

and use it as

fun1(1,2)

which was messier.

Should I arrange all those function in a class as attributes, or just put them all in a file?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 3
    modules are a unit of organization. If you have no class constructors, inheritance, or staticly scoped methods, then you probably dont need classes – OneCricketeer Jan 20 '21 at 00:12
  • 1
    Agreed. There are some languages like Java where classes are used as a poor man's modules, because there's no better way. But in Python, we have actual modules and those should be used in this situation. – Silvio Mayolo Jan 20 '21 at 00:14
  • @OneCricketeer But what about nested function? say fun2(x)=fun1(x,x). With class, it could be achieved by "def fun2(x): return class1.fun1(x,x)" i.e. one would know where the function was coming from, even if it's itself. However, in module, "def fun2(x): return fun1(x,x)" had a default search path, and it might search in another places without being noticed.. How would I specify fun1 to be from module 1 or from another script? i.e. with class, one could more define the search path by specify the attributes. – ShoutOutAndCalculate Jan 20 '21 at 00:41
  • First of all, the first argument of a class instance method is always the instance of the class, so your example in the question should really be `def fun1(self, x, y)` to work as intended. Classes have nothing to do with whether or not you can/should nest functions. Calling/Returning the result of another function is not considered nesting. – OneCricketeer Jan 20 '21 at 03:05

0 Answers0