How are method default arguments overridden in python?

By default, default arguments can be overridden:

>>> 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 this considered bad style?

+3


source to share


3 answers


You can change the signatures of overridden methods in any 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 this considered bad style?

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

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



In other words, the derived class must fulfill all the contracts provided by the base class. In particular, overridden methods must have the same signatures and similar semantics. Since Python doesn't help you with this, you have to manage it manually using your IDE (Intellij IDEA here):

enter image description here

To answer your specific question about overriding default options, I think the answer is "depends". If the parameter is a parameter that is only used internally and does not affect the observed behavior of the object, there is nothing wrong with changing it:

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

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

      

on the other hand, if param significantly affects semantics, it is part of the contract and should not 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):

      

+5


source


This is definitely allowed, but can be very confusing for your callers. Can't they use the object D

as if it were an object B

?



0


source


How is this possible?
What is the mechanism?

You just overwrite the entire method in the derived class.

0


source







All Articles