I am learning about inheritance in Python and I was experimenting with superclasses and the super() function. Here is my code:
class Person: def __init__(self, name, age, weight): self.name = name self.age = age self.weight = weight def describe(self): return f"{self.name}, {self.age}, {self.weight}" class Engineer(Person): def __init__(self, name, age, weight): super().__init__("Bla bla", 10, 100) self.name = name self.age = age self.weight = weight self.occupation = "Engineer" def describe(self): return super().describe() my_engineer = Engineer("Larry", 17, 120) print(my_engineer.describe()) I have a Java background, and apparently super() works differently in Python than it does in Java. In Java, the output of code equivalent to this would be Bla bla, 17, 120, but this code is outputting Larry, 17, 120. Why is this code printing out Larry, 17, 120 rather than what I expected it to? To my understanding, I am instantiating the class Engineer and passing in "Larry", 17, and 120 to __init__, but then I pass in "Bla bla", 10, and 100 to the superclass's __init__, so the superclass should be initialized with those values. Then when I call my_engineer.describe(), it should call describe() in the superclass and use the superclass's passed in values. But apparently, this is not what is happening. Can anyone explain what is going on?
__init__, explicitly; why is that surprising?super()works differently in Python than in Java. As a note of advice, it's best not to try to project concepts learned in one language on another language you're learning. While languages do have certain broad aspects in common (inheritance, in this case), the way these concepts are implemented are often very different. When learning a new language, It's best to treat it as a separate, unique language, without importing other ideas from other languages learned.