Reputation: 3347
I have encountered a problem with modifying a hierarchy of classes when I want to add a member variable to a base class, which necessitates a rewrite of constructors in derived classes.
For example, I have something like this:
class Animal:
___init___(self,animal_name):
self.name = animal_name
class Cat(Animal):
___init__(self,animal_name,animal_pattern):
self.pattern = animal_pattern
super().__init__(self,animal_name)
Now, suppose I add "age" member variable to class Animal
:
class Animal:
___init___(self,animal_name,animal_age):
self.name = animal_name
self.age = animal_age
class Cat(Animal):
___init__(self,animal_name,animal_age,animal_pattern):
self.pattern = animal_pattern
super().__init__(animal_name,animal_age)
This change required me to add animal_age
as a parameter in the constructor of Cat
. If the hierarchy of derived classes contains many classes, this quickly becomes tedious and error prone. Is there a way to avoid this rewrite, both in terms of language features or design ideas?
Upvotes: 1
Views: 30
Reputation: 1153
I understand why it might seem tedious but there is no way around it. Every subclass must have the required arguments to pass to its parent class. It would also be fairly annoying if this wasn't the case. Let's say you don't have to explicitely type animal_name
and animal_age
. Now it becomes very difficult for the person creating a Cat
instance to know what arguments are required. Currently you have all the required arguments visible in Cat
.
You could use the *argv
functionality but this will only make your code very confusing.
Upvotes: 1