Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

python - Changing instance attributes of a parent class from a child class

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"
question from:https://stackoverflow.com/questions/65849044/changing-instance-attributes-of-a-parent-class-from-a-child-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...