Junior — Middle
How do inheritance mechanisms differ in Python and C#?
sobes.tech AI
Answer from AI
In Python and C#, inheritance mechanisms share common features, but there are also important differences:
-
Python:
- Supports multiple inheritance — a class can inherit from multiple base classes.
- Uses the Method Resolution Order (MRO) to determine the order of method calls in multiple inheritance.
- All classes by default inherit from the base class
object. - Inheritance is dynamic; attributes and methods can be changed at runtime.
-
C#:
- Supports only single inheritance — a class can inherit from only one base class.
- Implements multiple inheritance through interfaces — a class can implement multiple interfaces.
- Inheritance is strictly typed and static.
Example of multiple inheritance in Python:
class A:
def method(self):
print("A")
class B:
def method(self):
print("B")
class C(A, B):
pass
c = C()
c.method() # Prints "A" according to MRO
In C#, this is implemented via interfaces:
interface IA { void Method(); }
interface IB { void Method(); }
class C : IA, IB {
public void Method() {
Console.WriteLine("C");
}
}
Thus, the main difference is that Python supports multiple class inheritance directly, while C# only supports single inheritance with multiple inheritance through interfaces.