Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to change the number of arguments of an overridden class method in Python?

Let's say I have a class written in Python like this:

class Foo(object):
    """My fake class"""

    def mymethod(self, first_arg):
        """original method"""
        pass

Now let's say I define a new class that extends the previous one and I want to override mymethod:

class Bar(Foo):
    """My new class"""

    def mymethod(self, first_arg, second_arg):
        """overridden method"""
        return first_arg == second_arg

Is it a bad practice to change the number of arguments in the overridden method?

EDIT:

Is there any official "good practice" rule about this? I just saw that if you do something like this in pydev you get a warning, so I suppose there should be something "official".

like image 525
Giovanni Di Milia Avatar asked Oct 18 '25 18:10

Giovanni Di Milia


1 Answers

I would say it's a bad idea unless you provide default values for your extra arguments. The way you have it, if you make an instance of Bar, anyone who doesn't know about Bar and only knows that your object is a Foo (which it is) will get an error if they try to use mymethod. But if you do def mymethod(self, first_arg, second_arg="some default"), then they will be okay even if they don't pass the second argument.

If you're able to do this, it often means you're just adding "details" to the method, and calls that don't supply those details will still work in a default way.

If you cannot create an appropriate default argument value, I would take that as a sign that you are defining behavior different enough that you need to make a new method instead.

like image 159
BrenBarn Avatar answered Oct 20 '25 06:10

BrenBarn