From 337b74d8d0819000273d7dc263f4d572df3f9b2b Mon Sep 17 00:00:00 2001 From: surister Date: Tue, 22 Oct 2019 10:27:22 +0200 Subject: [PATCH] add Python inheritance answers --- README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/README.md b/README.md index dc4ba3c..55e2b30 100644 --- a/README.md +++ b/README.md @@ -1692,6 +1692,69 @@ PEP8 is a list of coding conventions and style guidelines for Python
Explain inheritance and how to use it in Python
+``` +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. +``` +