Python类super与多继承问题:父类为何无打印输出?
It’s frustrating when your MRO looks right but the parent class’s output is nowhere to be found—let’s break down the most common culprits and fixes:
1. You Overrode the Method Without Calling super()
This is by far the most frequent issue. If your child class defines a method with the same name as the parent but doesn’t explicitly invoke the parent’s version via super(), the parent’s code won’t run—even if MRO lists the parent correctly.
Example of the problem:
class Parent: def greet(self): print("Hello from Parent!") class Child(Parent): def greet(self): print("Hello from Child!") # No super() call here # Calling Child's greet() only runs the child's code child = Child() child.greet() # Output: Hello from Child!
Fix it by adding super() to trigger the parent’s method:
class Child(Parent): def greet(self): super().greet() # Calls Parent's greet() first print("Hello from Child!") child.greet() # Output: # Hello from Parent! # Hello from Child!
2. Multiple Inheritance Is Redirecting the Method Call
If you’re using multiple inheritance, double-check that the parent class you expect is actually the next in line for the method in your MRO. Even if MRO looks correct, if another parent class in the hierarchy defines the same method, it will be called instead of your intended parent.
Example:
class ParentA: def greet(self): print("Hello from ParentA!") class ParentB: def greet(self): print("Hello from ParentB!") class Child(ParentA, ParentB): def greet(self): super().greet() # Calls ParentA's greet() first (per MRO) child = Child() print(Child.__mro__) # Output: (Child, ParentA, ParentB, object) child.greet() # Output: Hello from ParentA!
If you expected ParentB’s output, adjust your inheritance order or explicitly call ParentB.greet(self) in the child’s method.
3. A Typo Is Preventing Method Overriding
Double-check that the method name in the child exactly matches the parent’s. A tiny typo (like greet() vs greet_()) means the child isn’t overriding the parent’s method at all—so when you call the child’s method, it never triggers the parent’s code.
This also applies to special methods like __init__ or __str__: if your parent has an __init__ that prints something, but the child’s __init__ doesn’t call super().__init__(), the parent’s initialization code won’t run.
4. The Parent’s Method Isn’t Being Called At All
Wait—are you actually invoking the method that should trigger the parent’s code? For example, if you defined my_method() in the parent but you’re calling another_method() in the child, the parent’s my_method() won’t run unless it’s called explicitly.
Quick Debug Tip: Add a print statement directly in the parent’s method to confirm it’s being executed. If it doesn’t show up, trace back to where you’re invoking the method in your code—you might be calling the wrong one.
内容的提问来源于stack exchange,提问作者user504909

