Home > OS >  Inheritance in class with only class methods vs modules
Inheritance in class with only class methods vs modules

Time:05-04

I defined two classes and I just want to use their methods all over my application without instantiating them. I read a lot of opinions around this and many suggest using modules instead of classes in such a case. Fair play, but what about inheritance?

Let's say I have a class Dog, and another class AgressiveDog, which inherits from Dog:

class Dog:
    sound = 'Woof'

    @classmethod
    def bark(cls):
        print(cls.sound)

class AgressiveDog(Dog):

    @classmethod
    def bark(cls):
        super().bark()
        super().bark()

I'd translate the above classes to the below modules (please shout if there's a better way).

dog.py:

sound = 'Woof'

def bark():
    print('Woof')

agressivedog.py:

import dog

def bark():
    dog.bark()
    dog.bark()

Is the 'modules' way of solving this preferred over classes in such case?

With modules I have to create two separate .py files for things that are a lot related to each other, plus when I work in agressivedog.py I have to always remember to explicitly use the methods and attributes from the parent (dog.py).

With classes, I could just have both classes in one .py file and my only crime is that I'm not planning to instantiate those classes. What am I missing?

CodePudding user response:

In your case, there is no difference. Here we are talking about the extensibility of the code. Let's imagine that you have 50 classes of "dog" heirs. Accordingly, you will have 50 modules, which is pretty bad, and the inheritance hierarchy will be very confusing. What am I talking about? If you understand that your structure will be limited to 2-3 heirs, then use modules, but for good support, testability and extensibility, use classes.

  • Related