inheritance in python
This commit is contained in:
parent
1f2c365a35
commit
58b6c7c644
1 changed files with 29 additions and 2 deletions
|
|
@ -55,8 +55,9 @@ print(p1.name)
|
||||||
|
|
||||||
Key points to note:
|
Key points to note:
|
||||||
|
|
||||||
- The `__init__` method is the constructor function and must exist on every
|
- The `__init__` method is the constructor function. You only need to provide it
|
||||||
class to define the properties of the class
|
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
|
- `self` is a reference to the class itself and the object it will create, akin
|
||||||
to `this` in other languages
|
to `this` in other languages
|
||||||
- You must pass `self` as a parameter to every method (this is a difference from
|
- 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
|
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
|
## Object references
|
||||||
|
|
||||||
When you log a class you get a reference to its hexadecimal memory reference.
|
When you log a class you get a reference to its hexadecimal memory reference.
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue