eolas/zk/Abstract_base_classes_in_Python.md

45 lines
1.2 KiB
Markdown
Raw Permalink Normal View History

2026-01-21 18:33:46 +00:00
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.