3

So I am making a mario clone in pygame and I have a base class Character and two sub classes, Mario and Luigi. The methods that the Character class defines require a significant amount of attributes from a sub class (around 20) to be defined. For example, the initial y velocity of the Character instance must be defined. Should I be passing all these attributes to the Character class as parameters or should I just have them defined in the sub class (ie. Mario or Luigi)? Or what about a mix? My thinking is that since these properties are all required for a Character instance to have, that they should all be passed as parameters in the constructor of the class.

Here's some pseudo-code to demonstrate what I mean:

class Mario(Character):

    def __init__(self):
        Character.__init__(self, 1, 2, 3, 4, 5, ... 20)

class Character:

    def __init__(self, var1, var2, var3, var4, var5, ... var20):
        pass

OR

class Mario(Character):

    def __init__(self):
        var1 = 1
        var2 = 2
        var3 = 3
        var4 = 4
        ...
        var20 = 20
        Character.__init__(self)

class Character:

    def __init__(self):
        pass
  • 2
    Firstly, are you sure Mario and Luigi should be sub-classes, rather than instances, of Character? Secondly, a long parameter list is a code smell in itself; could you group some of them together into a new object? Finally, passing the parameters to the base class (using super) is the right thing to do, as it means you can easily change how they're handled later. – jonrsharpe Aug 16 '15 at 7:30
  • How so would it make it easier to handle the attributes later? @jonsharpe – Robbie Aug 17 '15 at 1:58
  • Well, imagine you add some form of checking into __init__ that applies to both sub-classes - if you do it in the base class, you only need to implement it once. Indeed, even with just the assignments from parameters to attributes, you're typing the same thing twice for no reason. – jonrsharpe Aug 17 '15 at 14:30
4

I would suggest defining your common properties in the base class and simply assign them as such in the constructor for your child class. I would also put sanity checks ensuring that your necessary properties are set before you can use a given character on your field/map.

You shouldn't need to pass all of the properties to the constructor as this will reduce clarity in your actual code... Seeing a constructor setting properties defined in the base is probably more clear, especially if they don't all need to be set, or if there are additional properties.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.