inheritance in python and TS
This commit is contained in:
parent
58b6c7c644
commit
ef78c806c2
2 changed files with 44 additions and 0 deletions
44
zk/Abstract_base_classes_in_Python.md
Normal file
44
zk/Abstract_base_classes_in_Python.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
In [TypeScript](./Classes_in_TypeScript.md) we can use interfaces to implement
|
||||
classes and use `abstract` to create abstract methods:
|
||||
|
||||
```ts
|
||||
interface Person {
|
||||
firstName: string;
|
||||
calculateAge(): number;
|
||||
}
|
||||
|
||||
class Programmer implements Person {}
|
||||
// Must include the property firstName and the method calculateAge
|
||||
```
|
||||
|
||||
```ts
|
||||
abstract class Person {
|
||||
abstract calculateAge(): number;
|
||||
}
|
||||
|
||||
class Child extends Person {}
|
||||
// Must concretize the abstract calculateAge method from the parent class
|
||||
```
|
||||
|
||||
The same --or very similar-- functionality can be achieved in Python by
|
||||
importing the `abc` module ("Abstract Base Class").
|
||||
|
||||
```py
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
class Person(ABC):
|
||||
@abstractmethod
|
||||
def calculate_age(self):
|
||||
pass
|
||||
|
||||
|
||||
class Child(Person):
|
||||
def calculate_age(self):
|
||||
# Must concretize the abstract method in Person
|
||||
```
|
||||
|
||||
> Only use `@abstractmethod` if the method _must_ exist on the child and _must_
|
||||
> be defined in the child (not the parent). If you just want to redefine a
|
||||
> parent method, you can use
|
||||
> [normal inheritance](./Class_inheritance_in_Python.md). Python will interpret
|
||||
> the methods upwards from the child, before getting to the parent.
|
||||
Loading…
Add table
Reference in a new issue