diff --git a/zk/Abstract_base_classes_in_Python.md b/zk/Abstract_base_classes_in_Python.md new file mode 100644 index 0000000..a3e0d85 --- /dev/null +++ b/zk/Abstract_base_classes_in_Python.md @@ -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. diff --git a/zk/Classes.md b/zk/Classes_in_TypeScript.md similarity index 100% rename from zk/Classes.md rename to zk/Classes_in_TypeScript.md