{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 46. 재사용 가능한 @property 메서드를 만들려면 디스크립터를 사용하라"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "@property의 가장 큰 문제점은 재사용성이다.\n",
    "\n",
    "@property가 데코레이션하는 메서드를 같은 클래스에 속하는 여러 애트리뷰트로 사용할 수는 없다.\n",
    "\n",
    "그리고 서로 무관한 클래스 사이에서 @property 데코레이터를 적용한 메서드를 재사용할 수도 없다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Homework:\n",
    "    def __init__(self):\n",
    "        self._grade = 0\n",
    "    \n",
    "    @property\n",
    "    def grade(self):\n",
    "        return self._grade\n",
    "    \n",
    "    @grade.setter\n",
    "    def grade(self, value):\n",
    "        if not (0 <= value <= 100):\n",
    "            raise ValueError(\n",
    "                '정수는 0과 100 사이입니다.')\n",
    "        self._grade = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "galileo = Homework()\n",
    "galileo.grade = 95"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Exam:\n",
    "    def __init__(self):\n",
    "        self._writing_grade = 0\n",
    "        self._math_grade = 0\n",
    "    \n",
    "    @staticmethod\n",
    "    def _check_grade(value):\n",
    "        if not (0 <= value <= 100):\n",
    "            raise ValueError(\n",
    "                '정수는 0과 100 사이입니다.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "이런식으로 계속 확장하려면, 시험과목을 이루는 각 부분마다 새로운 @property를 지정하고 관련 검증 메서드를 작성해야한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Exam:\n",
    "    def __init__(self):\n",
    "        self._writing_grade = 0\n",
    "        self._math_grade = 0\n",
    "\n",
    "    @staticmethod\n",
    "    def _check_grade(value):\n",
    "        if not (0 <= value <= 100):\n",
    "            raise ValueError(\n",
    "                '점수는 0과 100 사이입니다')\n",
    "\n",
    "    @property\n",
    "    def writing_grade(self):\n",
    "        return self._writing_grade\n",
    "\n",
    "    @writing_grade.setter\n",
    "    def writing_grade(self, value):\n",
    "        self._check_grade(value)\n",
    "        self._writing_grade = value\n",
    "\n",
    "    @property\n",
    "    def math_grade(self):\n",
    "        return self._math_grade\n",
    "\n",
    "    @math_grade.setter\n",
    "    def math_grade(self, value):\n",
    "        self._check_grade(value)\n",
    "        self._math_grade = value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "게다가 이런 접근 방법은 일방적이지도 않다.\n",
    "\n",
    "더 나은 방법은 디스크립터를 사용하는 것이다.\n",
    "\n",
    "디스크립터 프로토콜은 파이썬 언어에서 애트리뷰트 접근을 해석하는 방법을 정의한다.\n",
    "\n",
    "디스크립터 클래스는 __get__과 __set__ 메서드를 제공하고, 이 두 메서드를 사용하면 별다른 준비 코드 없이도 원하는 점수 검증 동작을 재사용할 수 있다.\n",
    "\n",
    "이런 경우 같은 로직을 한 클래스 안에 속한 여러 다른 애트리뷰트에 적용할 수 있으므로 디스크립터가 믹스인보다 낫다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Grade:\n",
    "    def __init__(self):\n",
    "        self._value = 0\n",
    "        \n",
    "    def __get__(self, instance, instance_type):\n",
    "        return self._value\n",
    "    \n",
    "    def __set__(self, instance, value):\n",
    "        if not (0 <= value <= 100):\n",
    "            raise ValueError(\n",
    "                '점수는 0과 100 사이입니다')\n",
    "        self._value = value\n",
    "\n",
    "class Exam:\n",
    "# 클래스 애트리뷰트\n",
    "    math_grade = Grade()\n",
    "    writing_grade = Grade()\n",
    "    science_grade = Grade()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "exam = Exam()\n",
    "exam.writing_grade = 40"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "Exam.__dict__['writing_grade'].__set__(exam, 40)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "40"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exam.writing_grade"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "40"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Exam.__dict__['writing_grade'].__get__(exam, Exam)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "이런 동작을 이끌어내는 것은 object의 __getattribute__ 메서드다.\n",
    "\n",
    "간단히 말해, Exam 인스턴스에 writing_grade라는 이름의 애트리뷰트가 없으면 파이썬은 Exam 클래스의 애트리뷰트를 대신 사용한다.\n",
    "\n",
    "이 클래스의 애트리뷰트가 __get__과 __set__ 메서드가 정의된 객체라면 파이썬은 디스크립터 프로토콜을 따라야한다고 결정한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "쓰기 82\n",
      "과학 99\n",
      "두 번째 쓰기 점수 75 맞음\n",
      "첫 번째 쓰기 점수 75 틀림; 82점이어야 함\n"
     ]
    }
   ],
   "source": [
    "first_exam = Exam()\n",
    "first_exam.writing_grade = 82\n",
    "first_exam.science_grade = 99\n",
    "print('쓰기', first_exam.writing_grade)\n",
    "print('과학', first_exam.science_grade)\n",
    "\n",
    "second_exam = Exam()\n",
    "second_exam.writing_grade = 75\n",
    "print(f'두 번째 쓰기 점수 {second_exam.writing_grade} 맞음')\n",
    "print(f'첫 번째 쓰기 점수 {first_exam.writing_grade} 틀림; '\n",
    "      f'82점이어야 함')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "하지만 이 구현은 잘못되었다.\n",
    "\n",
    "Eaxm 여러 객체에 대해 접근하면 위와 같이 나온다.\n",
    "\n",
    "애트리뷰트로 한 Grade 인스턴스를 모든 Exam 인스턴스가 공유한다.\n",
    "\n",
    "이를 해결하려면 Grade 클래스가 각각의 유일한 Exam 인스턴스에 대해 따로 값을 추적하게 해야한다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from weakref import WeakKeyDictionary\n",
    "class Grade:\n",
    "    def __init__(self):\n",
    "        self._values = WeakKeyDictionary()\n",
    "\n",
    "    def __get__(self, instance, instance_type):\n",
    "        if instance is None:\n",
    "            return self\n",
    "        return self._values.get(instance, 0)\n",
    "\n",
    "    def __set__(self, instance, value):\n",
    "        if not (0 <= value <= 100):\n",
    "            raise ValueError(\n",
    "                '점수는 0과 100 사이입니다')\n",
    "        self._values[instance] = value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "그냥 dictionary로 할 시 메모리 리킹이 발생한다.\n",
    "\n",
    "따라서 WeakKeyDictionary를 사용할 수 있다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Exam:\n",
    "    # 클래스 애트리뷰트\n",
    "    math_grade = Grade()\n",
    "    writing_grade = Grade()\n",
    "    science_grade = Grade()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "첫 번째 쓰기 점수 82 맞음\n",
      "두 번째 쓰기 점수 75 맞음\n"
     ]
    }
   ],
   "source": [
    "first_exam = Exam()\n",
    "first_exam.writing_grade = 82\n",
    "second_exam = Exam()\n",
    "second_exam.writing_grade = 75\n",
    "print(f'첫 번째 쓰기 점수 {first_exam.writing_grade} 맞음')\n",
    "print(f'두 번째 쓰기 점수 {second_exam.writing_grade} 맞음')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 기억해야 할 내용\n",
    "- @property 메서드의 동작과 검증 기능을 재사용하고 싶다면 디스크립터 클래스를 만들라.\n",
    "- 디스크립터 클래스를 만들 떄는 메모리 누수를 방지하기 위해 WeakKeyDictionary를 사용하라.\n",
    "- __getattribute__가 디스크립터 프로토콜을 사용해 애트리뷰트 값을 읽거나 설정하는 방식을 정확히 이해하라."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}