1

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)?

2
  • What are "such problems"? Commented Oct 5, 2019 at 22:58
  • @Aran-Frey thats a good question. The book is not clear about it imho (the example used before to show issues with super() uses a method without changing the signature). The "problem" mentioned is, that one needs a thourough understanding of method resolution order and how super() determines which attributes to use. Commented Oct 5, 2019 at 23:07

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sence. The example in the book is also not with the init method. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.