natter1
natter1

Reputation: 394

Do not change signature of methods when subclassing?

I'm reading Pro Python 3. There in chapter 4 classes super() and its pitfalls is explained, with the final conclusion: "the only defense against such problems is an agreement among all classes involved to not change method signatures"

Sadly I'm not sure what that means. Wouldn't this kill the purpose of subclassing? Or how would be the "pythonic" way to do the following without changing the signature of __init__?:

class Geometry2d:
    def __init__(self, rotation_angle=0, destination=Point(0, 0)):
        # do something

class Rectangle(Geometry2d):
    def __init__(self, width, height, rotation_angle=0, destination=Point(0, 0)):
        super().__init__(rotation_angle,  destination)
        self.width = width
        self.height = height
        # ...

As far as I understood, I changed the signature by adding two arguments (width and height) to the subclass Rectangle.__init__ and also changed the parameter order (arguments with default parameter at the end)?

Upvotes: 1

Views: 414

Answers (1)

user2357112
user2357112

Reputation: 282148

The reason to not change method signatures in subclasses is so that you can take an instance of class Foo and call methods of Foo on that instance without needing to know the exact subclass to know what arguments to pass.

That doesn't apply to __init__ (except in multiple inheritance, which is one of the reasons it's so easy to get multiple inheritance wrong). You always know what __init__ you're going to invoke (except in multiple inheritance), so changing the signature of __init__ in a subclass is fine (except in multiple inheritance).

Upvotes: 1

Related Questions