San Jose State University Department of Applied Data Science
**DATA 200 Computational Programming for Data Analytics**
Spring 2024 Instructor: Ron Mak
"
]
},
{
"cell_type": "markdown",
"id": "005cc9a4-05ba-4eb5-8fc7-d7d633d7d80d",
"metadata": {},
"source": [
"# Autogenerated Classes"
]
},
{
"cell_type": "markdown",
"id": "fd13f546-d64e-45d5-b047-76e20431ce5e",
"metadata": {},
"source": [
"#### Recall the class `Card` in source file `card.py` from a few weeks ago."
]
},
{
"cell_type": "markdown",
"id": "b2ab7e36-77e1-4fdb-90c3-bc027fe9671a",
"metadata": {},
"source": [
"#### We can use Python's **autogeneration** feature to automatically generate boilerplate code that's common in most classes."
]
},
{
"cell_type": "markdown",
"id": "ab8fb788-b9f0-41f6-82de-d7f1ab35d9b9",
"metadata": {},
"source": [
"#### We need to import `dataclass` from the built-in `dataclasses` module, and `ClassVar` and `List` from the build-in `typing` module. See source file `carddataclass.py`.\n",
"```\n",
"from dataclasses import dataclass\n",
"from typing import ClassVar, List\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "0022509c-7ffa-4d92-b066-305b8d8cade1",
"metadata": {},
"source": [
"#### The `@dataclass` decorator indicates a data class. A data class declare both class attributes and data attributes inside the class but outside the class methods. Data classes require additional information (*hints*) to distinguish class attributes from data attributes. These hints affect how the autogenerated methods are implemented.\n",
"```\n",
"@dataclass\n",
"class Card:\n",
" FACES: ClassVar[List[str]] = ['Ace', '2', '3', '4', '5', '6', '7', \n",
" '8', '9', '10', 'Jack', 'Queen', 'King']\n",
" SUITS: ClassVar[List[str]] = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n",
"\n",
" face: str\n",
" suit: str\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "ad87e22f-76f6-4332-a372-1476d877f32d",
"metadata": {},
"source": [
"#### In the above, the **variable annotation** `ClassVar[List[str]]` is a type hint that specifies `FACES` and `SUITS` are class variables that refer to lists of strings. On the other hand, `face` and `suit` are data attributes that belong to each instantiated object."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}