0

I have a constructor in my parent class that takes four parameters. In my subclass, I need to have one that takes three parameters. In the parent class I the first parameter is length. The subclass will have a set length.

I have tried many things, but none of them have worked. The one in the code that I added is one of them.

    class X:
        def __init__(self, len, speed, locate, direction):
        self._len = len
        self._speed = speed
        self._locate = locate
        self._direction = direction

    from X import X

    class Y(X):
        def __int__(self, speed, locate, direction):
            super().__init__(speed, locate, direction)
            # one thing I've tried
            self._len = 3.0

When I create an object and try to pass three parameters in it says that I am missing a direction.

FredJacobs
  • 107
  • 1
  • 10

3 Answers3

0

Simply pass *args and **kwargs to both of your class inits:

class X:
    def __init__(self, len, speed, locate, direction, *args, **kwargs):
    self._len = len
    self._speed = speed
    self._locate = locate
    self._direction = direction

from X import X

class Y(X):
    def __int__(self, speed, locate, direction, *args, **kwargs):
        super().__init__(speed, locate, direction, *args, **kwargs)

If you are unsure about what the asterisk does, this question is a good resource.

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
  • Also note that you don't actually need `**kwargs` in your exact situation, but it's good practice to add them to class inits. – Lord Elrond Sep 17 '19 at 02:38
0

This works. You had a typo: def __int__( should be def __init__(

class X:
    def __init__(self, length, speed, locate, direction):
        self._len = length
        self._speed = speed
        self._locate = locate
        self._direction = direction


class Y(X):
    def __init__(self, speed, locate, direction):
        super().__init__(3.0, speed, locate, direction)


y = Y(10, 20, 30)

print(y._len, y._speed, y._locate, y._direction)
# prints 3.0 10 20 30
Emil Vatai
  • 2,298
  • 1
  • 18
  • 16
0

I would suggest below code

class Y(X):
        def __int__(self, speed, locate, direction):
            X.__init__(3.0, speed, locate, direction)

Here are some points to note

  • I prefer using parent class name (X) because it will be unambiguous incase of multiple inheritance
  • Now your y class use _len member of parent class
  • I would suggest to avoid *args, **kwargs because explicit is better than implicit, you don't know what behaviour you want of new parameters added latter in superclass so it is better if it generates error in that case so you can explicitly decide what to do with them
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33