In my organization I came across versions of the following code:
from abc import ABC
class Animal(ABC):
def __init__(self, name=" "):
self.name = name
class Dog(Animal):
pass
class Cat(Animal):
pass
class Fish(Animal):
pass
collection: list[Animal] = [
Dog(),
Cat(),
Fish(),
]
The intended purpose (there might be other intentions as well) of this is to have the IDE (VSCode) have type hints for the various objects. However, we will have many Animal
s and none of the derived classes implements any features.
Wouldn't this follow DRY more closely:
class Animal:
def __init__(self, type, name=" "):
self.type = type
self.name = name
collection: list[Animal] = [
Animal(type="Dog"),
Animal(type="Cat"),
Animal(type="Fish"),
]
I do understand that the second implementation has the downside of allowing for arbitrary arguments for type
, maybe this could be avoided?
What's the right way to go about this? How to deal with a situation where classes are just existing to name things? Is this best practice?