From 58b6c7c644a410075da73066ca4558eec4be0d32 Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Wed, 21 Jan 2026 17:58:32 +0000 Subject: [PATCH] inheritance in python --- zk/Classes_in_Python.md | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/zk/Classes_in_Python.md b/zk/Classes_in_Python.md index 43515aa..615bc56 100644 --- a/zk/Classes_in_Python.md +++ b/zk/Classes_in_Python.md @@ -55,8 +55,9 @@ print(p1.name) Key points to note: -- The `__init__` method is the constructor function and must exist on every - class to define the properties of the class +- The `__init__` method is the constructor function. You only need to provide it + if you are defining properties at instantiation. If it's going to be empty, + don't bother. - `self` is a reference to the class itself and the object it will create, akin to `this` in other languages - You must pass `self` as a parameter to every method (this is a difference from @@ -106,6 +107,32 @@ class Person: return self.age < 20 ``` +## Inheritance + +Say that `TableService` is a child of `SqliteService`: + +```py +class TableService(SqliteService): +``` + +Say that the parent does something in the constructor, that you want to also do +in the child, or if you want to change the parent constuctor behaviour, you have +to invoke `super`: + +```py +class SqliteService: + def __init__(self, db_connection): + self.connection = db_connection + self.cursor = db_connection.cursor() + +class TableService(SqliteService): + def __init__(self, db_connection): + super().__init__(db_connection) + +``` + +See more in [Class inheritance in Python](./Class_inheritance_in_Python.md). + ## Object references When you log a class you get a reference to its hexadecimal memory reference.