{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4366758472" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id([1,2,3])" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Person:\n", " nationality = '대한민국'" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p1의 국적: 대한민국\n", "p2의 국적: 대한민국\n" ] } ], "source": [ "p1 = Person()\n", "p2 = Person()\n", "\n", "print('{}의 국적: {}'.format('p1', p1.nationality))\n", "print('{}의 국적: {}'.format('p2', p2.nationality))" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p1의 국적: 중국\n", "p2의 국적: 중국\n" ] } ], "source": [ "Person.nationality = '중국'\n", "\n", "print('{}의 국적: {}'.format('p1', p1.nationality))\n", "print('{}의 국적: {}'.format('p2', p2.nationality))" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p1의 국적: 일본\n", "p2의 국적: 일본\n" ] } ], "source": [ "Person.nationality = '일본'\n", "\n", "print('{}의 국적: {}'.format('p1', p1.nationality))\n", "print('{}의 국적: {}'.format('p2', p2.nationality))" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [], "source": [ "class Person:\n", " def __init__(self, name, nationality):\n", " \"\"\"객체가 생성될 때 실행되는 내부 함수\"\"\"\n", " self.name = name\n", " self.nationality = nationality" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# 같은 종류의 정보로 구성된 여러 개의 정보 생성\n", "p1 = Person('이성주', '대한민국')\n", "p2 = Person('토니 스타크', 'USA')\n", "p3 = Person('클라크 켄트', 'USA')" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "이성주(대한민국)\n", "토니 스타크(USA)\n", "클라크 켄트(크립톤)\n" ] } ], "source": [ "p3.nationality = '크립톤'\n", "for p in [p1, p2, p3]:\n", " print('{}({})'.format(p.name, p.nationality))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Person:\n", " def __init__(self, name, nationality):\n", " self.name = name\n", " self.nationality = nationality\n", " \n", " def say_name(self):\n", " print('이름: {}'.format(self.name))" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "p1 = Person('이성주', '대한민국')\n", "p2 = Person('토니 스타크', 'USA')\n", "p3 = Person('클라크 켄트', '크립톤')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p1, Person)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p1, dict)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "이름: 이성주\n", "이름: 토니 스타크\n", "이름: 클라크 켄트\n" ] } ], "source": [ "for p in [p1, p2, p3]:\n", " p.say_name()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "dict 을 사용했다면?" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "이름: 이성주\n" ] } ], "source": [ "p1 = {'name':u'이성주', 'nationality': u'대한민국'}\n", "p2 = {'user_name':u'토니 스타크', 'nationality': u'USA'}\n", "\n", "def say_name(profile):\n", " if not isinstance(profile, dict):\n", " return\n", " if 'name' in profile:\n", " print(u'이름: {}'.format(profile['name']))\n", "\n", "say_name(p1)\n", "say_name(p2)\n", "say_name(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 클래스 영역과 객체 영역의 차이" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Person:\n", " number_of_people = 0\n", " def __init__(self, name, nationality):\n", " self.name = name\n", " self.nationality = nationality\n", " Person.number_of_people += 1\n", " \n", " def say_name(self):\n", " print('이름: {}'.format(self.name))" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "outputs": [], "source": [ "p1 = Person('이성주', '대한민국')\n", "p2 = Person('토니 스타크', 'USA')\n", "p3 = Person('클라크 켄트', '크립톤')" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "print(Person.number_of_people)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "print(p1.number_of_people)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n" ] } ], "source": [ "Person.number_of_people += 1\n", "print(Person.number_of_people)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "p1.number_of_people += 1\n", "print(p1.number_of_people)" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "0\n" ] } ], "source": [ "p1.number_of_people = 0\n", "print(Person.number_of_people)\n", "print(p1.number_of_people)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 도전과제\n", "\n", "카지노에 오는 사람들은 이름, 성별, 자본금 정보를 갖는다. 각 사람의 정보를 저장하는 클래스를 정의한다.\n", "\n", "a. 자본금을 원화(KRW) 또는 달러화(USD)로 출력할 수 있도록 클래스를 정의하고 객체를 생성한다.\n", "\n", "isinstance(p,Player) --> True\n", "\n", "p.show_money(currency='KRW') --> 이성주의 자본금: 510,000 원 \n", "p.show_money(currency='USD') --> 이성주' budget: 500 USD \n", "\n", "b. 각 사람은 게임에 참가한 결과 자본금이 변할 수 있다. 자본금의 변화를 반영할 수 있는 클래스의 메소드를 정의한다.\n", "\n", "p.change_capital(10) --> 이성주의 자본금: 510 USD (+10)\n", "\n", "p.change_capital(-30) --> 이성주의 자본금: 500 USD (-10)\n", "\n", "c. 각 함수에는 적절한 자료형의 인자가 할당되어야 한다. 적절하지 않은 자료형의 인자가 할당되었을 때는 예외 처리를 수행해 프로그램이 비정상적으로 종료되지 않게 작성한다." ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "자본금을 0으로 지정합니다.\n", "이성주\n", "이성주's budget: 0.0\n", "이성주의 자본금: 0.0\n", "이성주 님은, 남성입니다.\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "class Player:\n", " def __init__(self, name, isFemale, capital):\n", " self.name = name\n", "\n", " if not isinstance(isFemale, bool):\n", " # 불리언 형식이 아니면 ValueError 예외 발생\n", " # 객체 생성 실패\n", " raise ValueError\n", "\n", " self.isFemale = isFemale\n", " \n", " try:\n", " # 숫자 값으로 변환 시도\n", " self.capital = float(capital)\n", " # TODO: 음수 확인\n", " except:\n", " # 변환에 실패하면, 자본금의 값을 0으로 설정\n", " print('자본금을 0으로 지정합니다.')\n", " self.capital = 0.0\n", " \n", " def set_capital(self):\n", " pass\n", " \n", " def show_gender(self):\n", " \"\"\"출력 예시: 이성주 님은 남성/여성입니다.\"\"\"\n", " msg = u'{} 님은, {}입니다.'\n", " if self.isFemale:\n", " msg = msg.format(self.name, u'여성')\n", " else:\n", " msg = msg.format(self.name, u'남성')\n", " \n", " # 입출력은 되도록 마지막에 몰아서\n", " print(msg)\n", "\n", " return self.isFemale\n", " \n", " def show_money(self, currency='USD'):\n", " currency_rate = {'KRW': 1100, \n", " 'USD': 1}\n", " \n", " # TODO: 만약 capital의 값이 숫자가 아니라면?\n", " # TODO: capital이 음수가 될 수 있을까?\n", " currency_converted = self.capital * currency_rate[currency]\n", " \n", " if currency == 'KRW':\n", " msg = u'{}의 자본금: {}'\n", " else:\n", " msg = u\"{}'s budget: {}\"\n", "\n", " \n", " print(msg.format(self.name, currency_converted))\n", " \n", " return currency_converted\n", " \n", " def change_capital(self, delta):\n", " self.capital += delta\n", " return self.capital\n", " \n", "# 객체 생성 \n", "p = Player(u'이성주', False, '5백 달러')\n", "print(p.name)\n", "p.show_money()\n", "p.show_money(currency='KRW')\n", "result = p.change_capital(+10)\n", "p.show_gender()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 도전과제\n", "\n", "SJ 카지노는 블랙잭, 룰렛 두 가지 게임을 제공한다. 각 게임에는 참가자들이 1 명 이상 참가할 수 있다. SJ 카지노를 Casino 클래스로 정의하고, 클래스 내에서 각 게임들을 정의하시오.\n" ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from __future__ import print_function\n", "import random\n", "\n", "class Casino:\n", " def __init__(self, capital=10000000):\n", " self.capital = capital\n", " \n", " def generate_card(self):\n", " # 52장 카드 덱 생성\n", " suits = ['Heart', 'Diamond', 'Clover', 'Spade']\n", " ranks = range(2,11)+['J', 'Q', 'K', 'A']\n", " deck = []\n", " for s in suits:\n", " for r in ranks:\n", " card = s + str(r)\n", " deck.append(card)\n", " random.shuffle(deck)\n", " return deck\n", " \n", " def get_card_value(self, hand):\n", " \"\"\"카드패의 숫자값 합계\"\"\"\n", " # 현재 hand의 카드의 숫자를 모두 더한다.\n", " value=0\n", " for card in hand:\n", " # 현재 카드의 숫자값\n", " rank = card[1]\n", " if rank=='A':\n", " value = value + 14\n", " elif rank=='K':\n", " value = value + 13\n", " elif rank == 'Q':\n", " value = value + 12\n", " elif rank == 'J':\n", " value = value + 11\n", " else:\n", " # 숫자인 경우는 그냥 더해준다.\n", " value = value + rank\n", " \n", " return value\n", " \n", " def play_blackjack(self, players, output_file=None):\n", " # 블랙잭 게임 시작\n", " deck=self.generate_card()\n", " \n", " # 각 참가자에 대해\n", " for p in players:\n", " # 카드 첫 두 장 받기\n", " p['hand'] = [deck.pop(), deck.pop()]\n", " \n", " # TODO: 여러 명이 참가할 수 있는 블랙잭 규칙 적용 ...\n", "\n", " # 게임 결과를 파일로 출력\n", " if output_file is not None:\n", " f = open(output_file, 'a')\n", " text_encoded = play_log.encode('utf-8')\n", " f.write(text_encoded)\n", " f.close()\n", " \n", " def play_roulette(self, players, output_file=None):\n", " \"\"\"룰렛(Roulette)는 돌아가는 바퀴라는 의미인데 \n", " 0으로부터 36까지 37~38개의 눈금으로 나눈 회전반 \n", " 가운데 1개의 알을 넣고 돌리다가 정지했을 때 \n", " 알이 어느 눈금에 정지하느냐를 맞추는 노름이다.\"\"\"\n", " \n", " # 1. 각 플레이어 베팅\n", " bettings = []\n", " for p in players:\n", " # 각 플레이어 베팅 시뮬레이션\n", " bet_number = random.randint(0,36)\n", " # 베팅은 10 단위 이상, 참가자의 자본금 이하 액수로 무작위\n", " if p.capital < 10:\n", " continue\n", " bet = random.randint(10, p.capital)\n", " p.change_capital(-1*bet)# 베팅 액수만큼 감액\n", " bettings.append((p, bet_number, bet))\n", " \n", " # 2. 룰렛 돌리기\n", " spin = random.randint(0,36)\n", " \n", " # 3. 승패 확인\n", " winners = []\n", " for bet in bettings:\n", " if bet[1] == spin:\n", " # 승리!\n", " winners.append(bet[0]) \n", " \n", " # 4. 베팅 분배\n", " # 전체 베팅 금액을 승리자의 숫자로 균등 분배\n", " bet_total = 0\n", " for bet in bettings:\n", " bet_total += bet[2]\n", " \n", " if len(winners) == 0:\n", " print(u'House always wins')\n", " self.capital += bet_total\n", " print(self.capital)\n", " return\n", " \n", " reward = float(bet_total)/len(winners)\n", " for p in winners:\n", " p.change_capital(reward)\n", " \n", " # TODO: 결과 파일 출력력" ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "House always wins\n", "10001129\n", "House always wins\n", "10002988\n", "House always wins\n", "10003256\n", "House always wins\n", "10003321\n", "House always wins\n", "10003451\n", "House always wins\n", "10003483\n", "House always wins\n", "10003494\n", "House always wins\n", "10003494\n", "House always wins\n", "10003494\n", "이성주's budget: 0.0\n", "신수현's budget: 2.0\n", "유한별's budget: 1.0\n", "김경철's budget: 3.0\n" ] } ], "source": [ "casino = Casino()\n", "\n", "p1 = Player(u'이성주', False, 500)\n", "p2 = Player(u'신수현', True, 1000)\n", "p3 = Player(u'유한별', False, 800)\n", "p4 = Player(u'김경철', False, 1200)\n", "\n", "players = [p1, p2, p3, p4]\n", "\n", "for i in range(10):\n", " casino.play_roulette(players)\n", "\n", "# 게임이 끝난 후 각 참가자들의 자본금 출력\n", "for p in players:\n", " p.show_money()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 상속" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Person:\n", " def __init__(self, name, isFemale, nationality):\n", " self.name = name\n", " self.isFemale = isFemale\n", " self.nationality = nationality\n", " \n", " def say_name(self):\n", " print(u'이름: {}'.format(self.name))" ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "이름: 이성주\n" ] } ], "source": [ "class Player(Person):\n", " def __init__(self, name, isFemale, nationality, capital):\n", " Person.__init__(self, name, isFemale, nationality)\n", "\n", "player = Player(u'이성주', False, u'대한민국', 1000)\n", "player.say_name()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "상속받은 기능 확장" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SJ 카지노 VIP!\n", "이름: 이성주\n" ] } ], "source": [ "class Player(Person):\n", " def __init__(self, name, isFemale, nationality, capital):\n", " Person.__init__(self, name, isFemale, nationality)\n", " \n", " \n", " def say_name(self):\n", " print(u'SJ 카지노 VIP!')\n", " Person.say_name(self)\n", " \n", " \n", "player = Player(u'이성주', False, u'대한민국', 1000)\n", "player.say_name()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 도전과제\n", "\n", "고양이과 동물은 다양한 방식의 울음소리를 낸다. 모든 고양이과 동물의 울음소리는 meow() 라는 메소드를 공통적으로 활용한다. 사자, 호랑이, 고양이의 클래스를 만들고, 다음과 같이 출력되도록 한다.\n", "\n", "출력예시:\n", "\n", "사자: 난 고양이과. '으르렁'\n", "\n", "호랑이: 난 고양이과. '어흥'\n", "\n", "고양이: 난 고양이과. '야옹'" ] }, { "cell_type": "code", "execution_count": 104, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "고양이: 난 고양이과. 야옹\n" ] } ], "source": [ "class Cat:\n", " def __init__(self):\n", " self.whoami = u'고양이'\n", " self.sound = u'야옹'\n", " self.category = u'고양이과'\n", " \n", " def meow(self):\n", " msg = u'{}: 난 {}. {}'.format(\n", " self.whoami, self.category, self.sound)\n", " return msg\n", " \n", "cat = Cat()\n", "print(cat.meow())" ] }, { "cell_type": "code", "execution_count": 109, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "사자: 난 고양이과. 으르렁사자: 난 고양이과. 으르렁\n" ] } ], "source": [ "class Lion(Cat):\n", " def __init__(self):\n", " Cat.__init__(self)\n", " self.whoami = u'사자'\n", " self.sound = u'으르렁'\n", " \n", " def meow(self, multiple):\n", " msg = Cat.meow(self)\n", " return msg * multiple\n", " \n", "lion = Lion()\n", "print(lion.meow(2))" ] }, { "cell_type": "code", "execution_count": 110, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(cat, Cat)" ] }, { "cell_type": "code", "execution_count": 111, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(lion, Lion)" ] }, { "cell_type": "code", "execution_count": 116, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "instance" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(lion)" ] }, { "cell_type": "code", "execution_count": 112, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(lion, Cat)" ] }, { "cell_type": "code", "execution_count": 113, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(cat, Lion)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 다형성과 Duck Type" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Dog:\n", " def eat(self):\n", " print('낼름낼름')\n", "\n", "class Cat:\n", " def eat(self):\n", " print('홀짝홀짝')\n", "\n", "class Person:\n", " def eat(self):\n", " print('얌얌')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def dine(animal):\n", " animal.eat()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "낼름낼름\n", "홀짝홀짝\n", "얌얌\n" ] } ], "source": [ "dog = Dog()\n", "cat = Cat()\n", "me = Person()\n", "\n", "dine(dog)\n", "dine(cat)\n", "dine(me)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "질문: 자료형을 지정하지 않는데 부적절한 형태의 입력이 들어오면 문제가 되지 않나요?\n", "\n", "SJ: 네, 문제가 생깁니다." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Alien:\n", " def inhale(self):\n", " print('우리는 정기를 빨아들인다.')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "ename": "AttributeError", "evalue": "Alien instance has no attribute 'eat'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0malien\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mAlien\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdine\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0malien\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mdine\u001b[0;34m(animal)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdine\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0manimal\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0manimal\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0meat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: Alien instance has no attribute 'eat'" ] } ], "source": [ "alien = Alien()\n", "dine(alien) # Attribute 오류 발생!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Duck Typing\n", "\"오리처럼 걷고, 오리처럼 울면 오리\"\n", "\n", "질문: 그럼 자료형을 지정하지 않는 파이썬 같은 프로그래밍 언어는 안전하지 않은가요?\n", "\n", "SJ: 자료형을 지정하는 언어와 입력을 확인하는 방법이 다를 뿐이다. 자료형을 확인하는 것은 수단일 뿐 목적이 아님. 자료형을 확인 대신 예외처리를 적용." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def dine(animal):\n", " try:\n", " animal.eat()\n", " except AttributeError as ex:\n", " print('먹는게 뭔가요?')" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "먹는게 뭔가요?\n" ] } ], "source": [ "alien = Alien()\n", "dine(alien)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 상속" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a_list = [1,2,3]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(a_list, list)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(a_list, dict)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## 도전과제\n", "\n", "리스트, 문자열과 같은 시퀀스를 인자로 받아 무작위로 섞어서 반환하는 함수 shuffle_up를 정의하시오. 함수 내에서 random 모듈을 사용하시오.\n", "\n", "예: \n", " \n", " \n", " shuffled = shuffle_up([1,2,3])\n", " print(shuffled) # [3,1,2]\n", " shuffled = shuffle_up(u'파이썬')\n", " print(shuffled) # 썬파이" ] }, { "cell_type": "code", "execution_count": 119, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "파\n" ] }, { "ename": "TypeError", "evalue": "'unicode' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtext\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34mu'파이썬'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtext\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mtext\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34mu'아'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'unicode' object does not support item assignment" ] } ], "source": [ "text = u'파이썬'\n", "print(text[0])\n", "text[0] = u'아'" ] }, { "cell_type": "code", "execution_count": 123, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "bca\n" ] } ], "source": [ "from random import shuffle\n", "import string\n", "text = 'abc'\n", "text = list(text)\n", "shuffle(text)\n", "print(string.join(text, ''))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5, 7, 2, 1, 6, 4, 3, 8]\n" ] } ], "source": [ "from shuffle_up import shuffle_up\n", "\n", "result = shuffle_up([1,2,3,4,5,6,7,8])\n", "print(result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }