Last active
February 22, 2023 15:32
-
-
Save acbart/6a169e0e301d6634c8b512edec4a6859 to your computer and use it in GitHub Desktop.
Dataclass examples of common data structures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
@dataclass | |
class Teacher: | |
name: str | |
years_teaching: int | |
has_corgi: bool | |
courses: list[str] | |
me = Teacher("Dr. Bart", 6, True, ["CISC108", "CISC320"]) | |
print(me.name) | |
# Implementing a basic Linked List with dataclasses and strong static typing | |
@dataclass | |
class LinkedList: | |
pass | |
# Dummy node at end represents end of list | |
# Also called a Sentinel | |
TERMINAL_NODE = LinkedList() | |
# The actual data nodes | |
@dataclass | |
class LinkedNode(LinkedList): | |
data: int | |
next: LinkedList | |
# Equivalent to [5, 7, 3] | |
root = LinkedNode(5, LinkedNode(7, LinkedNode(3, TERMINAL_NODE))) | |
print(root.data, root.next.data, root.next.next.data) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment