{ "cells": [ { "cell_type": "markdown", "id": "238af8b7", "metadata": {}, "source": [ "# Python Basics - 12. Advanced OOP Essentials\n", "\n", "This notebook expands OOP topics with `@property`, class methods, static methods, and data classes. These patterns are widely used in production Python code." ] }, { "cell_type": "markdown", "id": "878e274a", "metadata": { "language": "markdown" }, "source": [ "## Download Notebook\n", "\n", "{download}`Download this notebook <12_advanced_oop.ipynb>`\n" ] }, { "cell_type": "markdown", "id": "4dfc91d7", "metadata": {}, "source": [ "## 1. `@property` for Controlled Attributes\n", "\n", "`@property` lets you expose method logic as if it were an attribute, helping enforce validation rules." ] }, { "cell_type": "code", "execution_count": null, "id": "b7435520", "metadata": {}, "outputs": [], "source": [ "class Circle:\n", " def __init__(self, radius):\n", " self.radius = radius\n", "\n", " @property\n", " def radius(self):\n", " return self._radius\n", "\n", " @radius.setter\n", " def radius(self, value):\n", " if value <= 0:\n", " raise ValueError(\"Radius must be positive\")\n", " self._radius = value\n", "\n", " @property\n", " def area(self):\n", " return 3.14159 * self.radius ** 2\n", "\n", "c = Circle(3)\n", "print(c.radius, c.area)" ] }, { "cell_type": "markdown", "id": "07c49ce3", "metadata": {}, "source": [ "## 2. Class Methods vs Static Methods\n", "\n", "- `@classmethod` receives `cls`, often used as alternative constructors.\n", "- `@staticmethod` does not receive `self` or `cls`; it's a utility function logically grouped inside a class." ] }, { "cell_type": "code", "execution_count": null, "id": "ab44826a", "metadata": {}, "outputs": [], "source": [ "class Temperature:\n", " def __init__(self, celsius):\n", " self.celsius = celsius\n", "\n", " @classmethod\n", " def from_fahrenheit(cls, fahrenheit):\n", " return cls((fahrenheit - 32) * 5 / 9)\n", "\n", " @staticmethod\n", " def is_freezing(celsius):\n", " return celsius <= 0\n", "\n", "t = Temperature.from_fahrenheit(68)\n", "print(t.celsius)\n", "print(Temperature.is_freezing(t.celsius))" ] }, { "cell_type": "markdown", "id": "33b56681", "metadata": {}, "source": [ "## 3. Data Classes\n", "\n", "`dataclasses` reduce boilerplate by auto-generating `__init__`, `__repr__`, and comparisons for data containers." ] }, { "cell_type": "code", "execution_count": null, "id": "bfbb5f08", "metadata": {}, "outputs": [], "source": [ "from dataclasses import dataclass\n", "\n", "@dataclass\n", "class Student:\n", " name: str\n", " score: float\n", "\n", "alice = Student(\"Alice\", 95.5)\n", "bob = Student(\"Bob\", 88.0)\n", "print(alice)\n", "print(alice.score > bob.score)" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }