From 9642cd7ae24f0ba79ce5647c709b35ae8f06a285 Mon Sep 17 00:00:00 2001 From: Jasper Ras Date: Sun, 19 Jan 2025 21:14:51 +0100 Subject: vault backup: 2025-01-19 21:14:51 --- 3 Resources/Python/Make dataclass dict-able.md | 15 +++++++++++++++ 3 Resources/Python/__getitem__ __setitem__.md | 5 +++++ 2 files changed, 20 insertions(+) create mode 100644 3 Resources/Python/Make dataclass dict-able.md create mode 100644 3 Resources/Python/__getitem__ __setitem__.md (limited to '3 Resources/Python') diff --git a/3 Resources/Python/Make dataclass dict-able.md b/3 Resources/Python/Make dataclass dict-able.md new file mode 100644 index 0000000..d8ee02b --- /dev/null +++ b/3 Resources/Python/Make dataclass dict-able.md @@ -0,0 +1,15 @@ +--- +tags: + - python + - "#how-to" +references: + - https://docs.python.org/3/library/functions.html#vars + - https://docs.python.org/3/reference/datamodel.html#object.__iter__ +--- +The `dict` method takes kwargs and creates a dict from that. If we want to pass an object into it the object implement the `__iter__` method. +We can use `vars` to make that easy: +``` +def __iter__(self): + for k, v in vars(self): + yield k, v +``` \ No newline at end of file diff --git a/3 Resources/Python/__getitem__ __setitem__.md b/3 Resources/Python/__getitem__ __setitem__.md new file mode 100644 index 0000000..03c890e --- /dev/null +++ b/3 Resources/Python/__getitem__ __setitem__.md @@ -0,0 +1,5 @@ +--- +tags: + - python +--- +To have a class behave as a dict it's possible to add the two magic methods `__getitem__(self, key)` and `__setitem__(self, key, val)`. \ No newline at end of file -- cgit v1.2.3