Home > Software engineering >  Do I have to override .__init__ in my subclass, or can I just add a few variables?
Do I have to override .__init__ in my subclass, or can I just add a few variables?

Time:11-01

In my Class Items(): I have an .__init__ function that initiates 7 variables. Then I have a subclass Toys(Items): it uses all 7 variables initiated as the Items 3 extra variables. All of the variables are set when the object is created.

Simplified Example of what I’m doing now:

Class Items():

    def __init__(self, name, color, size):
        self.name = name
        # etc. 

Class Toys(Items):
    def __init__(self, name, color, size, shape, noise)
        self.name = name
        # etc. 

I’ve tried, static variables but it doesn’t work since the variables affect all instances of Toys and each one needs to be different. I’ve tried using the Super function but it kicks errors for having too many args. I’m currently working through @classmethod to see what happens.

Am I already doing it properly by overriding, or is there a better way to work the problem?

CodePudding user response:

you can use args, kewargs

class Items():
    def __init__(self, name, color, size):
        self.name = name
        self.color = color
        self.size = size

class Toys(Items):
    def __init__(self, shape, noise, *args, **kwargs):
        self.shape = shape
        self.noise = noise
        super().__init__(*args, *kwargs)
        
t = Toys('L', '12db', 'abc', 'red', '20cm')
t.color # red

CodePudding user response:

do you want to do something like this? This works but doesn't scale that well, and you might consider using kwargs etc. if you need it to be more flexible.

Class Items():

    def __init__(self, name, color, size):
        self.name = name
        self.color = color
        self.size = size
        # etc. 

Class Toys(Items):
    def __init__(self, name, color, size, shape, noise)
        super().__init__(name, color, size)
        self.shape = shape
        self.noise = noise
        # etc. 
  • Related