AlexP
AlexP

Reputation: 29

Group similar functions within objects

I am creating objects that contain the data in a pandas dataframe, and also many functions to import, query, modify and export the data to external files. I am doing this because I want the objects to contain the predefined complex pandas functions that we repeat frecuently.

The list of functions is growing quite a lot so I wanted to be able to group those functions somehow so they are nicelly accessed

Currenly I have id defined as:

class myclass():
    def __init__(df):
        self.df = df
    def f1(self):
        print("Hello World")
    def f2(self,bar,foo)
        return self.df[["bar","foo"]].somefunction()
# many more functions...
        def f40():
            self.df.rename(...,inplace=True)

And I use it like this:

a = myclass(df)
a.f1()
a.f2(bar,foo)
a.f40()

I would like however to group it by import functions (i), query functions (q), manipulating functions (m) and output functions (o) so the sintax would look like this

a = myclass()
a.i.f1()
a.o.f2(bar,foo)
a.m.f40()

What is the best way forward to do this?

Edit:

Upvotes: 1

Views: 63

Answers (1)

6c1
6c1

Reputation: 402

One option would be to create a class for each group of functions, and include them in your main class (a technique called class composition):

class InputController:
    """Import functions"""
    ...


class QueryController:
    """Query functions"""
    ...


class ManipulationController:
    """Manipulation functions"""
    ...


class OutputController:
    """Output functions"""
    ...
    def foo(self): print("Hello World")


class MyClass:
    def __init__(self):
        self.i = InputController()
        self.q = QueryController()
        self.m = ManipulationController()
        self.o = OutputController()



...
>>> MyClass().o.foo()
Hello World!

Upvotes: 3

Related Questions