How are method default arguments overridden in python?

9.7k views Asked by At

Method default arguments can be overridden apparently:

>>> class B:
...     def meth(self, r=True): print r
>>> class D(B):
...     def meth(self, r=False): print r
... D().meth()
False
>>> B().meth()
True

How is this possible ? Is it considered bad style ?

3

There are 3 answers

0
georg On BEST ANSWER

You can change signatures of overridden methods in an arbitrary way. Python doesn't care:

class Base:
    def foo(self, x, y):
        pass

class Deriv(Base):
    def foo(self, blah=100):
        pass

but if you ask

Is it considered bad style ?

the answer is Yes, because it violates the important Liskov substitution principle:

if Deriv extends Base, you must be able to replace all occurrences of Base with Deriv without breaking your program.

In other words, a derived class must fulfill all contracts provided by the base class. Particularly, overridden methods must have same signatures and similar semantics. Since Python doesn't help you on that, you have to control that manually, with the help of your IDE (here Intellij IDEA):

enter image description here

To answer your specific question about overriding default params, I guess the answer is "it depends". If the param is an option that only used internally and doesn't affect the observable behavior of the object, there's nothing wrong about changing it:

class Buffer:
    def __init__(self, init_size=16):

class BigBuffer(Buffer):
    def __init__(self, init_size=1024):

on the other side, if the param substantially affects semantics, it's a part of the contract and shouldn't be overridden. For example, this code will be confusing

class Test:
    def test_equal(self, a, b, fail_if_equal=False):

class MyTest(Test):
    def test_equal(self, a, b, fail_if_equal=True):
1
Ned Batchelder On

It is definitely allowed, but could be very confusing for your callers. Shouldn't they be able to use a D object as if it were a B object?

0
GingerPlusPlus On

How is this possible ?
what is the mechanism ?

You simply overwrite whole method in derived class.