add Python inheritance answers
This commit is contained in:
parent
2522f5c324
commit
337b74d8d0
63
README.md
63
README.md
@ -1692,6 +1692,69 @@ PEP8 is a list of coding conventions and style guidelines for Python
|
|||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Explain inheritance and how to use it in Python</summary><br><b>
|
<summary>Explain inheritance and how to use it in Python</summary><br><b>
|
||||||
|
```
|
||||||
|
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.
|
||||||
|
```
|
||||||
|
|
||||||
</b></details>
|
</b></details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
|
Loading…
Reference in New Issue
Block a user