0

I have some classes that look like this.

class Parent:
    def f(self, x):
        # Is this bad practice?
        return x * self.number
    
class Child(Parent):
    def __init__(self, number):
        # We create number in Child.
        self.number = number

child = Child(2)
child.f(3) # 6 - this runs

It seems to be going against 'explicit is better than implicit' to define self.number in Parent without any indication that you must override it in Child. But it does run.

What's the best way to handle this? I could define it in Parent's __init__ but the user will only need to refer to Child and I don't want to duplicate the params passed to Parent and Child.

codeananda
  • 939
  • 1
  • 10
  • 16
  • 1
    The proper way is to make `Parent` an abstract class with an abstract attribute. See the duplicate above for how to declare abstract attributes. – deceze Feb 06 '23 at 13:31
  • I don't know that it even needs to be abstract. Just have `Parent.__init__` initialize the value, so that child classes need only use `super().__init__` (if they override `__init__` at all) to pass an appropriate value. – chepner Feb 06 '23 at 14:27
  • 1
    If you design your classes using the advice from https://rhettinger.wordpress.com/2011/05/26/super-considered-super/, you *don't* duplicate `number` in `Child` at all. – chepner Feb 06 '23 at 14:30

0 Answers0