0

I have imported some data (say, a few thousand transactions) into Pandas and now I have to perform some analysis on it. Examples include calculating variability, regression, etc. I was thinking of designing a class to import and store the data in an object and then calling methods on it. However, a lot of the objectives, which I thought I could write as methods, are interdependent. In other words, method3 requires output from method2, which itself needs output from method1. So obviously, I cannot call data.method3() directly.

How do I design such a class?

Bigger question: Should I even design a class or just write a procedural code for such a problem?

bluetooth
  • 529
  • 6
  • 20

2 Answers2

0

It's perfectly fine for class methods to invoke other class methods, so you could have method2 call method1 and so on. Consider this example:

class MyDataHandler(object):
    def __init__(self, val):
        self.val = val

    def method1(self):
        return(2 * self.val)

    def method2(self):
        return(self.method1() + 1)

if __name__ == '__main__':
    data_handler = MyDataHandler(2)
    print(data_handler.method2())

Using OOP versus functional programming is a design decision and both styles work, so use a class if you want. Note that you could also store the output of e.g. method1 in a variable and then when method2 is run have it use the precomputed results of method1 if available.

0

You can simply call a dependency method from dependent method. See this simple example below:

def is_integer(n):
    # First Function, no dependency
    """ Validate is Integer"""
    return isinstance(n, int)


def sqaure(n):
    # Depends on "is_integer"
    if is_integer(n):
        return n * n
    return "Not a valid integer: '{}'".format(n)

def print_my_square(n):
    # Depends on "square"
    print sqaure(n)

Output:

>>> print_my_square('n')
Not a valid integer: 'n'
>>> print_my_square(99)
9801

Regarding your bigger question > "Bigger question: Should I even design a class or just write a procedural code for such a problem?"

Check this out when-should-i-be-using-classes-in-python

akshat
  • 1,219
  • 1
  • 8
  • 24
  • while this is the right direction, this isn't a class definition, and doesn't involve methods... – juanpa.arrivillaga Apr 25 '18 at 17:29
  • I understand, but user is unsure, if classes should should even be used. so I on how to handle dependency between functions. the same can be applied for class methods. – akshat Apr 26 '18 at 08:01