Why does super(Parent) inheritance not inherit parent init variables in Python?

  Kiến thức lập trình

I have a parent and child class. The child is initialized and should inherit all parent init variables (vars set in ini()). The child has 2 class variables and I want to inherit through super(Parent). I want to inherit this way cause it looks neat; the class variables are explicitly listed at the start and dont have to be passed through as additional argument to the parent init method.
Making an instance of the child results in an object with the child class variables assigned as instance variables and the parent init variables are not present. Why arent the parent init variables present in the object?

class Animal: 
    def __init__(self, name, age, legs) -> None:
        self.name = name
        self.age = age
        self.legs = legs
        self.color = "brown"


class Dog(Animal):
    sound: str = "bark"
    legs: int = 4
    
    def __init__(self, name, age) -> None:
        super(Animal)


d1 = Dog("Olaf", 2)

expected behaviour

>>> d1.name
Olaf
>>> d1.color
"brown"
>>> d2 = Dog("Pixel", 3)
>>> d1.legs
4
>>> d1.legs = 3
>>> d2.legs
3

actual behaviour


>>> d1.name
AttributeError: 'Dog' object has no attribute 'name'
>>> d1.color
AttributeError: 'Dog' object has no attribute 'color'
>>> d1.sound
'bark'
>>> d2 = Dog("Pixel", 3)
>>> d1.legs
4
>>> d1.legs = 3
>>> d2.legs
4
>>> d1.legs
3

the class variable “legs” gets picked up by the Animal init and is assigned to the dog instances. I expected that it would stay a class variable and that it would change for both dogs if the leg variable got changed in one of the dogs. Also that name and color would be callable, but they return AttributeErrors

I guess my question end up being: what does super(Parent) do and how does it compare to super().init()?

New contributor

CdRook is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT