1

I try to use multiple inheritance. Tank is both Vehicle and Weapon:

class Weapon:
    def __init__(self, name, strength, *args, **kwargs):
        super().__init__(*args, **kwargs)


class Vehicle:
    def __init__(self, name, average_speed, *args, **kwargs):
        super().__init__(*args, **kwargs)


class Tank(Weapon, Vehicle):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


Tank(name="Moshe", average_speed=68, weight=62.5, strength=17.7)

So the Tank's MRO is [__main__.Tank, __main__.Weapon, __main__.Vehicle, object].

Unfortunately, both Weapon and Vehicle have the name parameter, so currently the following error happens:

TypeError: __init__() missing 1 required positional argument: 'name'

Is there a non-artificial way to pass it through all the superclasses?

4
  • 1
    Your design is ambiguous. Is the weapon called Moshe or is the vehicle Moshe? Looking at the code I don't know. Are expecting both to be Moshe? That wouldn't be my first guess. Perhaps the name should be a property of the Tank? MAybe the Tank should use composition rather than inheritance? Seems to me that a tank is not a weapon for example, but it may have a few. Commented Jun 28, 2020 at 8:31
  • Why do the init of Weapon and Vehicle take arguments at all, if you ignore them? You do not need (or should) call super on classes which only inherit (implicitly) from object. Commented Jun 28, 2020 at 8:41
  • Weapon and Vehicle could both inherit from another class that stores the name. But as kabanus already said: a Tank is not a weapon, it consists of one (or even multiple) Weapons. Commented Jun 28, 2020 at 8:55
  • Is Weapon.name and Vehicle.name actually supposed to have the same meaning? Is there a reason why "thing with name" isn't a separate type, i.e. class Tank(Weapon, Vehicle, Named):? Commented Jun 28, 2020 at 9:25

1 Answer 1

2

I'm guessing you intend for name to mean essentially the same thing in either constructor. The first thing that comes to mind is to make a superclass that consumes it only once:

class Named:
    def __init__(self, name, *args, **kwargs):
        pass

class Weapon(Named):
    def __init__(self, strength, *args, **kwargs):
        super().__init__(*args, **kwargs)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.