0

Consider the following class:

class Car():
    def __init__(self, model):
        self.model = model

If I wanted to define specific models, I could do something like this:

class FordGT(Car):
    model = "Ford GT"
    def __init__(self):
        Car.__init__(self,self.model)

In that way, I could create a large amount of different car models. The only problem with doing this though, is that for every car model, I am repeating the init function.

def __init__(self):
    Car.__init__(self,self.model)

Code repetition to me is always a sign of bad code. How could I fix this? Is it possible to pass init arguments to the parent without using an init on a child?

1
  • I used a car example just to simplify, but in fact I have a series of regular expressions, where each class defines a pattern I'm searching for. I then define all the processing functions in the parent class, so as to avoid repeating code. Commented Feb 17, 2017 at 15:38

1 Answer 1

1

Firstly, you need to drop that over-broad assumption. Repeated code is not necessarily bad code, if by repeating something you make the code as a whole clearer.

Secondly, though, I don't understand why you need the __init__ at all, or the call to the superclass method. self.model is the same when accessed from a method originally defined on the subclass as it is from a method originally defined on the superclass; that is the whole point of inheritance. So you can just use that attribute throughout.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, I didn't need the inits at all. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.