Hello,
I am just learning programming with Python as my first language.
I want to build a small application to manage electronic parts.
All parts share some global attributes: ipn, mpn, dpn, manufacturer...
But then there are additional attributes that only parts from a specific category have.
For example a capacitor will have these additional attributes: dielectric, volts...
I've done it this way:
However in the child class I have to repeat all arguments in line 12 and 13.
If I want to add an attribute to the parent class, I'll have to write it twice(!) in every single child class too?
If I have 10 child classes I'll need to add it in 20 places...
That sounds insane and absolutely wrong to me.
Am I doing it wrong? Is there an easier way?
And another question:
I want to add a method to print out the object's attributes.
But since the parent and sub classes will have different attributes, I am not sure where to create this method.
Should I create it in the parent and control which attributes to print with
Or should I create one print method in every child class? (Which means I have to repeat some parts over and over)
What's best practice here?
Thank you in advance
I am just learning programming with Python as my first language.
I want to build a small application to manage electronic parts.
All parts share some global attributes: ipn, mpn, dpn, manufacturer...
But then there are additional attributes that only parts from a specific category have.
For example a capacitor will have these additional attributes: dielectric, volts...
I've done it this way:
# Define parent class class Part(): def __init__(self, ipn, mpn, dpn, man): self.ipn = ipn self.mpn = mpn self.dpn = dpn self.manufacturer = man # Define child class class PartCapacitor(Part): def __init__(self, ipn, mpn, dpn, man, dielectric): super().__init__(ipn, mpn, dpn, man) self.dielectric = dielectricA programming rule I've already learned is: "Dont repeat yourself".
However in the child class I have to repeat all arguments in line 12 and 13.
If I want to add an attribute to the parent class, I'll have to write it twice(!) in every single child class too?
If I have 10 child classes I'll need to add it in 20 places...
That sounds insane and absolutely wrong to me.
Am I doing it wrong? Is there an easier way?
And another question:
I want to add a method to print out the object's attributes.
But since the parent and sub classes will have different attributes, I am not sure where to create this method.
Should I create it in the parent and control which attributes to print with
if
statements?Or should I create one print method in every child class? (Which means I have to repeat some parts over and over)
What's best practice here?
Thank you in advance
