Sobes.tech
Junior — Middle

Can you explain the concept of inheritance in object-oriented programming in Python?

sobes.tech AI

Answer from AI

Inheritance in object-oriented programming allows creating a new class based on an existing one, inheriting its properties and methods. In Python, this is implemented by specifying the base class in the definition of the new class.

For example:

class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

my_pet = Dog()
my_pet.speak()  # Outputs: Dog barks

Here, the Dog class inherits from Animal and overrides the speak method. Inheritance allows code reuse and the creation of class hierarchies.

Although the question pertains to Python, in C# the inheritance concept is similar, but the syntax differs.