Python Refactoring – Should a Python Class with Many Methods Be Split into Multiple Classes?

classpythonrefactoring

I have a class that will end up having more than ~30 methods. They all make sense to be part of the same class because they require access to the same data.

However, does it make any sense to split up a large class into several smaller abstract classes (by functionality, type, use, etc.) and have the main class extend (i.e. multiple inheritance) from all the smaller classes?

Best Answer

No.

If you create several different classes and inherit them all in a single class you've haven't really improved the situation. You've just one class which is pretending to be a whole bunch of classes. You've made the implementation a lot more complicated and you haven't actually separated the pieces at all. If A inherits from B and C, then A is as complicated as B and C.

Having more than 30 methods does suggest it could benefit from being split up. Maybe there is a clever way to split it up. Sometimes you just can't, and in that case I do recommend have a large class. But often there are clever ways to break the object into several objects.