Skip to content

Commit

Permalink
Tweaks to OOP
Browse files Browse the repository at this point in the history
  • Loading branch information
ecomodeller committed Nov 20, 2023
1 parent 1bd96f7 commit 8da1720
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions 05_oop.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,21 @@ class DataArray:
...
```

. . .

`DataArray` *has a* `geometry` (e.g. `Grid`) and an `item` (`ItemInfo`).

## Inheritance

::: {.incremental}

* Inheritance is a way to reuse code and specialize behavior.
* A child class inherits the attributes and methods from the parent class.
* A child class can override the methods of the parent class.
* A child class can add new methods.

:::

## Inheritance - Example

```{mermaid}
Expand Down Expand Up @@ -166,6 +179,11 @@ class GeometryFMVerticalProfile{
_GeometryFMLayered <|-- GeometryFMVerticalProfile
```

. . .

`GeometryFM3D` inherits from `_GeometryFMLayered`, it *is a* `_GeometryFMLayered`.


## Inheritance - Example (2)

```python
Expand All @@ -180,6 +198,7 @@ class _GeometryFMLayered(_GeometryFM):
self._n_sigma = n_sigma
```


## Composition vs inheritance

::: {.incremental}
Expand Down Expand Up @@ -226,14 +245,13 @@ def repeated_string(s, n):

::: {.incremental}
* Python is a dynamically typed language
* Types are not checked at compile time
* Types are checked at runtime
* Types are not checked at compile time by the interpreter
* Types *can* be checked before runtime using a linter (e.g. `mypy`)
* Type hints can be used by VS Code to provide auto-completion
:::

. . .

**Python** with type hints

```python
n: int = 2
s: str = "Hello"
Expand Down Expand Up @@ -379,6 +397,9 @@ Dundermethods:

```python
class JavaLikeToolbox:

def __init__(self, tools: Collection[Tool]):
self.tools = tools

def getToolByName(self, name: str) -> Tool:
for tool in self.tools:
Expand All @@ -401,6 +422,9 @@ Hammer()
```python
class Toolbox:

def __init__(self, tools: Collection[Tool]):
self._tools = {tool.name: tool for tool in tools}

def __getitem__(self, name: str) -> Tool:
return self._tools[name]

Expand Down

0 comments on commit 8da1720

Please sign in to comment.