-2

I'm trying to make it so that when a Boxer object is created there is no need to specify the breed as it is automatically set to Boxer

class Dog:
    def __init__(self, name, age, breed):
        # instance attributes
        self.name = name
        self.age = age
        self.breed = breed
class Boxer(Dog):

    super().__init__().breed = "Boxer"

    def speak(self,sound = 'woof'):
        print(f'{self.name} says {noise}')

hettie = Boxer('Hettie',5)
hettie.speak()

At the moment when I run this code I get this error:

RuntimeError: super(): no arguments

I tried initially to put the super() line inside the __init__() method but then I had an issue with not enough arguments when I called Boxer

def __init__(self):
    super().breed = "boxer"

but if I added arguments I still had issues

def __init__(self,breed):
    super().breed = "boxer"
dev1610
  • 23
  • 5
  • It's unclear what your attempted `__init__` implementation was, but I would expect something like `def __init__(self, name, age): super().__init__(name, age, "Boxer")`. Calling the no-args super in the class body certainly won't work. – jonrsharpe Jan 22 '21 at 16:29
  • Also `__init__` always returns None, you will get an error if you try to set the `.breed` atribute at `super().__init__().breed = "Boxer"` – Countour-Integral Jan 22 '21 at 16:33

1 Answers1

1

You need to put your call to super()'s method inside the __init__ method.

def __init__(self, name, age): # Also provide all the parameters
    super(Boxer, self).__init__(name, age, breed="Boxer") 

Notice that you can optionally provide the classname Boxer and the instance self to super as arguments (if you don't it will be done automatically) and you also need to provide all the arguments passed in the __init__ method into the super().__init__ method. Because the constructor __init__ always returns None you cannot modify any of it's attributes like you did. You just have to set self.breed = "Boxer" or just pass in "Boxer" as the parameter to the cosntructor.

Countour-Integral
  • 1,138
  • 2
  • 7
  • 21
  • Thanks. This worked `def __init__(self, name, age): super(Boxer, self).__init__(name, age, breed="boxer")`. Is there any documentation I can read on this as the python docs for classes don't really explain any of this – dev1610 Jan 22 '21 at 16:48
  • 1
    @Henry Garrett [here](https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods). – Countour-Integral Jan 22 '21 at 17:04