Skip to content

Latest commit

 

History

History
66 lines (45 loc) · 1.54 KB

inheritance.md

File metadata and controls

66 lines (45 loc) · 1.54 KB

Inheritance

Explain what is inheritance and how does it work in Python

Solution

By definition inheritance is the mechanism where an object acts as a base of another object, retaining all its properties.

So if Class B inherits from Class A, every characteristics from class A will be also available in class B. Class A would be the 'Base class' and B class would be the 'derived class'.

This comes handy when you have several classes that share the same functionalities.

The basic syntax is:

class Base: pass

class Derived(Base): pass

A more forged example:

class Animal: def init(self): print("and I'm alive!")

def eat(self, food):
    print("ñom ñom ñom", food)

class Human(Animal): def init(self, name): print('My name is ', name) super().init()

def write_poem(self):
    print('Foo bar bar foo foo bar!')

class Dog(Animal): def init(self, name): print('My name is', name) super().init()

def bark(self):
    print('woof woof')

michael = Human('Michael') michael.eat('Spam') michael.write_poem()

bruno = Dog('Bruno') bruno.eat('bone') bruno.bark()

My name is Michael and I'm alive! ñom ñom ñom Spam Foo bar bar foo foo bar! My name is Bruno and I'm alive! ñom ñom ñom bone woof woof

Calling super() calls the Base method, thus, calling super().init() we called the Animal init.

There is a more advanced python feature called MetaClasses that aid the programmer to directly control class creation.