Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP - organising big classes [closed]

Tags:

python

oop

class

I am starting to write a big python library for some area of mathematics.

So I have this data structure (defined in class A) which represents a mathematical model.

I have a bunch of smaller functions, which I have put in A:

A.f(), A.g(),...

Which are more or less "helper functions" that are needed to calculate more important functions A.X(), A.Y(),... which the end user is interested in.

All of these functions of course depend on the data in A.

But the number of methods in A is growing and growing and getting confusing. How does one split such a class into smaller pieces. Lets say, the data structure with basic operations in it and the "methods" that do calculations on the structure?

What is the usual approach and the most pythonic approach?

like image 462
Jake B. Avatar asked Apr 26 '15 05:04

Jake B.


1 Answers

You can use pure functional approach and move methods that class users are not supposed to call on object instance to separate files.

In pure functional approach the functions don't depend on any internal state, have no side effects and calculate the return value based only on the arguments provided.

An example for illustration would be replacing the following:

# shape.py
class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

with:

# shape.py
class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y

# func.py
def area(shape):
    return shape.x * shape.y

Of course, it might be not a good idea to extract area method of the Shape class into a separate function in another file, but you can definitely move all "helper functions" to separate files and call them properly from the class methods.

This will also greatly simplify helper function testing.

like image 168
krl Avatar answered Sep 21 '22 02:09

krl