{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 05-1 클래스\n", "\n", "### 클래스는 도대체 왜 필요한가?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "8\n" ] } ], "source": [ "# 계산기의 \"더하기\" 기능을 구현\n", "\n", "result = 0\n", "\n", "def adder(num):\n", " global result # 결과값을 유지하기 위해 전역 변수 사용\n", " result += num\n", "\n", " return result\n", "\n", "print(adder(3))\n", "print(adder(5))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "7\n", "3\n", "10\n" ] } ], "source": [ "# 한 프로그램에서 2개의 계산기가 필요한 경우 함수를 따로 만들어야 한다.\n", "\n", "result1 = 0\n", "result2 = 0\n", "\n", "def adder1(num):\n", " global result1\n", " result1 += num\n", " \n", " return result1\n", "\n", "def adder2(num):\n", " global result2\n", " result2 += num\n", " \n", " return result2\n", "\n", "print(adder1(3))\n", "print(adder1(4))\n", "\n", "print(adder2(3))\n", "print(adder2(7))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "7\n", "3\n", "10\n" ] } ], "source": [ "# 같은 함수를 반복해서 만드는 대신 클래스를 이용해서 구현\n", "\n", "class Calculator:\n", " def __init__(self):\n", " self.result = 0\n", " \n", " def adder(self, num):\n", " self.result += num\n", " \n", " return self.result\n", " \n", "cal1 = Calculator()\n", "cal2 = Calculator()\n", "\n", "print(cal1.adder(3))\n", "print(cal1.adder(4))\n", "\n", "print(cal2.adder(3))\n", "print(cal2.adder(7))\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 빼기 기능을 더한다고 해도 Calculator 클래스에 다음과 같은 함수를 추가해 주면 된다.\n", "\n", "```\n", "def sub(self, num):\n", " self.result -= num\n", " return self.result\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 클래스와 객체\n", "\n", "![과자틀과 과자](http://wikidocs.net/images/page/214/c1.png)\n", "\n", "- 과자틀: 클래스(class)\n", "- 과자틀로 만든 과자들: 객체(object)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 파이썬 클래스의 가장 간단한 예\n", "\n", "class Programmer:\n", " pass\n", "\n", "# Programmer 클래스의 객체를 만드는 방법\n", "\n", "kim = Programmer()\n", "park = Programmer()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [객체와 인스턴스의 차이]\n", "\n", "> 클래스에 의해서 만들어진 객체를 인스턴스라고도 한다. 객체와 인스턴스의 차이는 무엇일까?\n", "> kim = Programmer() 에서 kim 은 객체이다. 그리고 kim 이라는 객체는 Programmer 의 인스턴스이다.\n", "> 즉, 인스턴스라는 말은 특정 객체(kim)가 어떤 클래스(Programmer)의 객체인지를 관계 위주로 설명할 때 사용한다.\n", "> 즉, \"kim은 인스턴스\" 보다는 \"kim은 객체다\"라는 표현이 어울리며, \"kim은 Programmer의 객체\" 보다는 \"kim은 Programmer의 인스턴스\"라는 표현이 잘 어울린다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 클래스 기초 쌓기\n", "\n", "#### 클래스 변수" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Service:\n", " secret = \"영구는 외계인이다.\"\n", " \n", "pey = Service()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 외계인이다.'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pey.secret" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "juhoi = Service()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 외계인이다.'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "juhoi.secret" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "juhoi.secret = \"나는 외계인이다.\"" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 외계인이다.'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pey.secret" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 외계인이다.'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 클래스 변수 직접 접근하기\n", "\n", "Service.secret" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "Service.secret = \"영구는 도깨비이다.\"" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 도깨비이다.'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Service.secret" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 도깨비이다.'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pey.secret" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'나는 외계인이다.'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "juhoi.secret" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'영구는 도깨비이다.'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "duckbabys = Service()\n", "\n", "duckbabys.secret" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "도깨비 OST\n", "나는 외계인이다.\n", "도깨비 OST\n" ] } ], "source": [ "Service.secret = \"도깨비 OST\"\n", "\n", "print(pey.secret)\n", "print(juhoi.secret)\n", "print(duckbabys.secret)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### 클래스 내부의 함수(메서드)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 + 1 = 2 입니다\n" ] } ], "source": [ "class Service:\n", " secret = \"영구는 외계인이다.\"\n", " \n", " def sum(self, a, b):\n", " result = a + b\n", " \n", " print(\"%s + %s = %s 입니다\" % (a, b, result))\n", " \n", "\n", "pey = Service()\n", "\n", "pey.sum(1, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### self 살펴보기\n", "\n", "![메서드 self 파라미터](https://wikidocs.net/images/page/28/pey_sum.png)\n", "\n", "- 파이썬만의 특징: 객체를 통해 클래스의 함수를 호출할 때 호출한 객체 자신이 호출한 클래스 함수의 첫번째 입력 인수로 전될된다.\n", "- 다음과 같이 클래스를 통해 함수를 호출할 수도 있다. 이때는 객체가 자동으로 전달되지 않기 때문에 명시적으로 넘겨줘야 한다.\n", "\n", "```\n", "pey = Service()\n", "Service.sum(pey, 1, 1)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 객체 변수" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "홍길동 님 1 + 1 = 2 입니다.\n" ] } ], "source": [ "class Service:\n", " secret = \"영구는 외계인이다\"\n", " \n", " def setname(self, name):\n", " self.name = name\n", " \n", " def sum(self, a, b):\n", " result = a + b\n", " \n", " print(\"%s 님 %s + %s = %s 입니다.\" % (self.name, a, b, result))\n", " \n", "\n", "pey = Service()\n", "pey.setname(\"홍길동\")\n", "\n", "pey.sum(1, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### \\__init\\__ 이란 무엇인가?" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'Service' object has no attribute 'name'", "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[0mbabo\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mService\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[0mbabo\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msum\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m1\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;36msum\u001b[0;34m(self, a, b)\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"%s 님 %s + %s = %s 입니다.\"\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mresult\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mAttributeError\u001b[0m: 'Service' object has no attribute 'name'" ] } ], "source": [ "babo = Service()\n", "babo.sum(1,1)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "홍길동 님 1 + 1 = 2 입니다.\n" ] } ], "source": [ "class Service:\n", " secret = \"영구는 외계인이다\"\n", " \n", " def __init__(self, name): # 객체를 만들 때 항상 실행된다.\n", " self.name = name\n", " \n", " def sum(self, a, b):\n", " result = a + b\n", " \n", " print(\"%s 님 %s + %s = %s 입니다.\" % (self.name, a, b, result))\n", "\n", " \n", "pey = Service(\"홍길동\")\n", "\n", "pey.sum(1, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 클래스 자세히 알기\n", "\n", "#### 클래스의 구조\n", "\n", "```\n", "class 클래스이름[(상속 클래스명)]:\n", " <클래스 변수1>\n", " <클래스 변수2>\n", " ...\n", " \n", " def 메서드1(self[, 인수1, 인수2,,,]):\n", " <수행할 문장1>\n", " <수행할 문장2>\n", " ...\n", " \n", " def 메서드2(self[, 인수1, 인수2,,,]):\n", " <수행할 문장1>\n", " <수행할 문장2>\n", " ...\n", " \n", " ...\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 사칙연산 클래스 만들기\n", "\n", "#### 클래스를 어떻게 만들지 먼저 구상하기\n", "\n", "- 클래스명: FourCal\n", "- 피연산자를 설정해주는 메서드: setdata\n", "- 사칙연산을 해주는 메서드: sum, mul, sub, div" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class FourCal:\n", " def setdata(self, first, second):\n", " self.first = first\n", " self.second = second\n", " def sum(self):\n", " result = self.first + self.second\n", " return result\n", " def sub(self):\n", " result = self.first - self.second\n", " return result\n", " def mul(self):\n", " result = self.first * self.second\n", " return result\n", " def div(self):\n", " result = self.first / self.second\n", " return result\n", " \n", " \n", "a = FourCal()\n", "b = FourCal()\n", "\n", "a.setdata(4, 2)\n", "b.setdata(3, 7)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.sum()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.sub()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.mul()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.div()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.sum()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-4" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.sub()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "21" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.mul()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.42857142857142855" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.div()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"박씨네 집\" 클래스 만들기\n", "\n", "#### 클래스 구상하기\n", "\n", "- 클래스 이름은 HousePark 으로 하자. pey = HousePark()\n", "- pey.lastname 을 출력하면 \"박\"이라는 성을 출력하자.\n", "- 이름을 설정하면 pey.fullname 이 성을 포함한 값을 가지도록 하자.\n", "- 여행가고 싶은 장소를 입력하면 출력해 주는 travel 메서드로 만들어 보자. pey.travel(\"부산\")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class HousePark:\n", " lastname = \"박\"\n", " \n", " def __init__(self, name):\n", " self.fullname = self.lastname + name\n", " \n", " def travel(self, where):\n", " print(\"%s, %s 여행을 가다.\" % (self.fullname, where))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "__init__() missing 1 required positional argument: 'name'", "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[0;32m----> 1\u001b[0;31m \u001b[0mpey\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mHousePark\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: __init__() missing 1 required positional argument: 'name'" ] } ], "source": [ "pey = HousePark()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "pey = HousePark(\"응용\")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "박응용, 태국 여행을 가다.\n" ] } ], "source": [ "pey.travel(\"태국\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 클래스의 상속\n", "\n", "> class 상속받을 클래스명(상속할 클래스명)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class HouseKim(HousePark):\n", " lastname = \"김\"" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "김줄리엣, 독도 여행을 가다.\n" ] } ], "source": [ "juliet = HouseKim(\"줄리엣\")\n", "juliet.travel(\"독도\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 메서드 오버라이딩" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class HouseKim(HousePark):\n", " lastname = \"김\"\n", " \n", " def travel(self, where):\n", " print(\"%s 은 %s 로 여행합니다.\" % (self.fullname, where))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "김줄리엣 은 독도 로 여행합니다.\n" ] } ], "source": [ "juliet = HouseKim(\"줄리엣\")\n", "juliet.travel(\"독도\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 연산자 오버로딩\n", "\n", "- 연산자(+, -, *, /)를 객체끼리 사용할 수 있게 하는 기법" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "박응용, 김줄리엣 결혼했네\n" ] } ], "source": [ "class HousePark:\n", " lastname = \"박\"\n", " def __init__(self, name):\n", " self.fullname = self.lastname + name\n", " def travel(self, where):\n", " print(\"%s, %s여행을 가다.\" % (self.fullname, where))\n", " def __add__(self, other):\n", " print(\"%s, %s 결혼했네\" % (self.fullname, other.fullname))\n", "\n", "\n", "class HouseKim(HousePark):\n", " lastname = \"김\"\n", " def travel(self, where):\n", " print(\"%s은 %s로 여행합니다.\" % (self.fullname, where))\n", "\n", "pey = HousePark(\"응용\")\n", "juliet = HouseKim(\"줄리엣\")\n", "pey + juliet" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 05-2 모듈\n", "\n", "- 모듈이란 함수나 변수 또는 클래스들을 모아 놓은 파일이다.\n", "- 다른 파이썬 프로그램에서 불러와 사용할 수 있게끔 만들어진 파일이라고도 할 수 있다.\n", "\n", "### 모듈 만들고 불러 보기" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing mod1.py\n" ] } ], "source": [ "%%writefile mod1.py\n", "def sum(a, b):\n", " return a + b" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\r\n", "04-sys1.py\r\n", "04-sys2.py\r\n", "04-새파일.txt\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb\r\n", "05장 파이썬 날개달기.ipynb\r\n", "mod1.py\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "import mod1\n", "\n", "print(mod1.sum(3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- **import** 는 이미 만들어진 파이썬 모듈을 사용할 수 있게 해주는 명령어\n", "- import 는 현재 디렉터리에 있는 파일이나 파이썬 라이브러리가 저장된 디렉터리에 있는 모듈만 불러올 수 있다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting mod1.py\n" ] } ], "source": [ "%%writefile mod1.py\n", "def sum(a, b):\n", " return a + b\n", "\n", "def safe_sum(a, b): \n", " if type(a) != type(b): \n", " print(\"더할수 있는 것이 아닙니다.\")\n", " return \n", " else: \n", " result = sum(a, b) \n", " return result" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\r\n", "04-sys1.py\r\n", "04-sys2.py\r\n", "04-새파일.txt\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb\r\n", "05장 파이썬 날개달기.ipynb\r\n", "__pycache__\r\n", "mod1.py\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n", "더할수 있는 것이 아닙니다.\n", "None\n" ] } ], "source": [ "import mod1\n", "\n", "print(mod1.safe_sum(3, 4))\n", "print(mod1.safe_sum(1, 'a'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [모듈 함수를 사용하는 또 다른 방법]\n", "\n", "> from 모듈이름 import 모듈함수" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from mod1 import sum\n", "\n", "sum(3, 4)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from mod1 import sum, safe_sum" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from mod1 import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if \\__name\\__ == \"\\__main\\__\": 의 의미" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting mod1.py\n" ] } ], "source": [ "%%writefile mod1.py\n", "def sum(a, b): \n", " return a+b\n", "\n", "def safe_sum(a, b): \n", " if type(a) != type(b): \n", " print(\"더할수 있는 것이 아닙니다.\")\n", " return \n", " else: \n", " result = sum(a, b) \n", " return result \n", "\n", "print(safe_sum('a', 1))\n", "print(safe_sum(1, 4))\n", "print(sum(10, 10.4))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "더할수 있는 것이 아닙니다.\n", "None\n", "5\n", "20.4\n" ] } ], "source": [ "%run mod1.py" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import mod1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "if __name__ == \"__main__\n", " print(safe_sum('a', 1))\n", " print(safe_sum(1, 4))\n", " print(sum(10, 10.4))\n", "```\n", "\n", "#### 알아두기\n", "\n", "- 파이썬의 \\__name\\__ 변수는 파이썬이 내부적으로 사용하는 특별한 변수명이다.\n", "- 직접 mod1.py 파일을 실행시킬 경우 mod1.py 의 \\__name\\__ 변수에는 \\__main\\__ 이라는 값이 저장된다.\n", "- 하지만, 모듈 mod1 을 import 할 셩우에는 mod1.py 의 \\__name\\__ 변수에는 \"mod1\" 이라는 값이 저장된다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [모듈을 불러오는 또 다른 방법]\n", "\n", "- sys.path.append(모듈을 저장한 디렉터리) 사용하기\n", " - sys.path 는 파이썬 라이브러리들이 설치되어 있는 디렉터리들을 보여준다." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['',\n", " '/usr/lib/python3.4',\n", " '/usr/lib/python3.4/plat-x86_64-linux-gnu',\n", " '/usr/lib/python3.4/lib-dynload',\n", " '/usr/local/lib/python3.4/dist-packages',\n", " '/usr/lib/python3/dist-packages',\n", " '/usr/local/lib/python3.4/dist-packages/IPython/extensions',\n", " '/root/.ipython']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sys\n", "sys.path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- PYTHONPATH 환경 변수 사용하기" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 05-3 패키지\n", "\n", "- 패키지(Packages)는 도트(.)를 이용하여 파이썬 모듈을 계층적으로 관리할 수 있게 한다.\n", "- 모듈명이 A.B 인 경우 A 는 패키지명이고 B 는 A 패키지의 B 모듈이 된다.\n", "\n", "*가상의 game 패키지 예*\n", "\n", "```\n", "game/\n", " __init__.py\n", " sound/\n", " __init__.py\n", " echo.py\n", " wav.py\n", " graphic/\n", " __init__.py\n", " screen.py\n", " render.py\n", " play/\n", " __init__.py\n", " run.py\n", " test.py\n", "```\n", "\n", "- game 디렉터리가 이 패키지의 루트 디렉터리이고 sound, graphic, play 는 서브 디렉터리이다.\n", "- .py 확장자를 가지는 파일은 파이썬 모듈이다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 패키지 만들기\n", "\n", "#### 기본 구성요소 준비하기\n", "\n", "- game 및 기타 서브 디렉터리를 생성하고 .py 파일을 만들어 보자" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "!mkdir game game/sound game/graphic" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\r\n", "04-sys1.py\r\n", "04-sys2.py\r\n", "04-새파일.txt\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb\r\n", "05장 파이썬 날개달기.ipynb\r\n", "__pycache__\r\n", "game\r\n", "mod1.py\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "touch: `gamd/graphic/__init__.py'를 touch할 수 없음: 그런 파일이나 디렉터리가 없습니다\n" ] } ], "source": [ "!touch game/__init__.py game/sound/__init__.py gamd/graphic/__init__.py" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "!touch game/graphic/__init__.py" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing game/sound/echo.py\n" ] } ], "source": [ "%%writefile game/sound/echo.py\n", "def echo_test():\n", " print(\"echo\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing game/graphic/render.py\n" ] } ], "source": [ "%%writefile game/graphic/render.py\n", "def render_test():\n", " print(\"render\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 패키지 안의 함수 실행하기" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "echo\n" ] } ], "source": [ "import game.sound.echo\n", "game.sound.echo.echo_test()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "echo\n" ] } ], "source": [ "from game.sound import echo\n", "echo.echo_test()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "echo\n" ] } ], "source": [ "from game.sound.echo import echo_test\n", "echo_test()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \\__init\\__.py 의 용도\n", "\n", "- \\__init\\__.py 파일은 해당 디렉터리가 패키지의 일부임을 알려주는 역할을 한다.(python3.3 버전부터는 없어도 인식된다)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### all 의 용도" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "echo\n" ] } ], "source": [ "from game.sound import *\n", "echo.echo_test()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 특정 디렉터리의 모듈을 * 를 이용하여 import 할 때에는 다음과 같이 해당 디렉터리의 \\__init\\__.py 파일에 \\__all\\__ 이라는 변수를 설정하고 import 할수 있는 모듈을 정의해 주어야 한다." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "!echo \"__all__ = ['echo']\" >> game/sound/echo.py" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "def echo_test():\r\n", " print(\"echo\")__all__ = ['echo']\r\n" ] } ], "source": [ "!more game/sound/echo.py" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "def echo_test():\r\n", " print(\"echo\")\r\n" ] } ], "source": [ "!more game/sound/echo.py" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__all__ = ['echo']\r\n" ] } ], "source": [ "!more game/sound/__init__.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 05-4 예외 처리\n", "\n", "- 프로그램을 만들다 보면 수많은 오류를 만나게 된다.\n", "- 때때로 이러한 오류를 무시하거나 별도로 처리하고 싶을때가 있다.\n", "- 파이썬은 try, except 를 이용해서 이러한 오류를 예외 처리한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 오류는 어떤 때 발생하는가?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: '없는파일'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\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[0;31m# 디렉터리 안에 없는 파일을 열려고 시도했을때 - FileNotFoundError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"없는파일\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '없는파일'" ] } ], "source": [ "# 디렉터리 안에 없는 파일을 열려고 시도했을때 - FileNotFoundError\n", "\n", "f = open(\"없는파일\", 'r')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\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[0;31m# 0으로 다른 숫자를 나누는 경우 - ZeroDivisionError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;36m4\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "# 0으로 다른 숫자를 나누는 경우 - ZeroDivisionError\n", "\n", "4 / 0" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "ename": "IndexError", "evalue": "list index out of range", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mIndexError\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 3\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mIndexError\u001b[0m: list index out of range" ] } ], "source": [ "# 리스트에서 얻을 없는 index 값 - IndexError\n", "\n", "a = [1, 2, 3]\n", "\n", "a[4]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### 오류 예외 처리 기법\n", "\n", "#### try, except 문\n", "\n", "- 기본구조\n", "\n", "```\n", "try:\n", " ...\n", "except [발생 오류[as 오류 메시지 변수]]:\n", " ...\n", "```\n", "\n", "- try 블록 수행 중 오류가 발생하면 except 블록이 수행된다.\n", "- except 구문은 다음의 3가지 방법으로 사용할 수 있다.\n", "\n", "\n", "1. try, except만 쓰는 방법: 오류 발생 시 종류에 상관없이 except 블록을 수행\n", "```\n", "try:\n", " ...\n", "except:\n", " ...\n", "```\n", "\n", "2. 발생 오류만 포함한 except문: except문에 미리 정해 놓은 오류만 except 블록을 수행\n", "```\n", "try:\n", " ...\n", "except 발생 오류:\n", " ...\n", "```\n", "\n", "3. 발생 오류와 오류 메시지 변수까지 포함한 except문\n", "```\n", "try\n", " ...\n", "except 발생 오류 as 오류 메시지 변수:\n", " ...\n", "```" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "division by zero\n" ] } ], "source": [ "try:\n", " 4 / 0\n", "except ZeroDivisionError as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### try .. else\n", "\n", "- else 절은 예외가 발생하지 않은 경우에 실행\n", "- 반드시 except 절 바로 다음에 위치" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Errno 2] No such file or directory: 'foo.txt'\n" ] } ], "source": [ "try:\n", " f = open(\"foo.txt\", 'r')\n", "except FileNotFoundError as e:\n", " print(str(e))\n", "else:\n", " data = f.read()\n", " f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### try .. finally\n", "\n", "- finally 절은 try 문 수행 도중 예외 발생 여부에 상관없이 항상 실행\n", "- 사용한 리소스를 close 해야 할 경우에 주로 사용" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "f = open(\"foo.txt\", 'w')\n", "\n", "try:\n", " # 무언가를 수행한다.\n", " pass\n", "finally:\n", " f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 여러개의 오류 처리하기\n", "\n", "- try 문 내에서 여러개의 오류를 처리하기 위해서는 다음과 같은 구문을 이용한다.\n", "\n", "```\n", "try:\n", " ...\n", "except 발생 오류1:\n", " ...\n", "except 발행 오류2:\n", " ...\n", "```" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "인덱싱 할 수 없습니다.\n" ] } ], "source": [ "try:\n", " a = [1, 2]\n", " print(a[3])\n", " 4/0\n", "except ZeroDivisionError:\n", " print(\"0으로 나눌 수 없습니다.\")\n", "except IndexError:\n", " print(\"인덱싱 할 수 없습니다.\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "list index out of range\n" ] } ], "source": [ "# 다음과 같이 2개 이상의 오류를 동시에 처리하기 위해서는 함께 묶어주어 처리하면 된다.\n", "\n", "try:\n", " a = [1, 2]\n", " print(a[3])\n", " 4/0\n", "except (ZeroDivisionError, IndexError) as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### 오류 회피하기\n", "\n", "- 특정 오류가 발생할 경우 그냥 통과시켜야 할 때 사용" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "try:\n", " f = open(\"없는 파일\", 'r')\n", "except FileNotFoundError:\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 오류 일부러 발생시키기\n", "\n", "- raise 를 사용하여 오류를 강제로 발생시킬 수 있다.\n", "- 예를 들어 Bird 라는 클래스를 상속받는 자식 클래스는 **반드시** fly 하는 함수를 구현하도록 만들고 싶은 경우\n", "\n", "```\n", "class Bird:\n", " def fly(self):\n", " raise NotImplementedError\n", "```\n", "\n", "> NotImplementedError 는 파이썬 내장 오류로, 꼭 작성해야 하는 부분이 구현되지 않았을 경우 일부러 오류를 발생시키고자 사용한다.\n", "\n", "```\n", "class Eagle(Bird):\n", " pass\n", " \n", "eagle = Eagle()\n", "eagle.fly()\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 오류 만들기\n", "\n", "- 특수한 경우에만 예외 처리를 하기 위해서 종종 오류를 만들어서 사용할 수도 있다.\n", "- 파이썬 내장 클래스인 **Exception** 블래스를 상속하여 만든다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class MyError(Exception):\n", " pass" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def say_nick(nick):\n", " if nick == '바보':\n", " raise MyError()\n", " print(nick)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "천사\n" ] }, { "ename": "MyError", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mMyError\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[0msay_nick\u001b[0m\u001b[0;34m(\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[0msay_nick\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'바보'\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;36msay_nick\u001b[0;34m(nick)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0msay_nick\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnick\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mnick\u001b[0m \u001b[0;34m==\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[0;32mraise\u001b[0m \u001b[0mMyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnick\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mMyError\u001b[0m: " ] } ], "source": [ "say_nick('천사')\n", "say_nick('바보')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "천사\n", "허용되지 않는 별명입니다.\n" ] } ], "source": [ "try:\n", " say_nick('천사')\n", " say_nick('바보')\n", "except MyError:\n", " print(\"허용되지 않는 별명입니다.\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "천사\n", "\n" ] } ], "source": [ "try:\n", " say_nick('천사')\n", " say_nick('바보')\n", "except MyError as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 오류 클래스에 \\__str\\__ 메서드를 구현해야 한다." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "천사\n", "허용되지 않는 별명입니다.\n" ] } ], "source": [ "class MyError(Exception):\n", " def __init__(self, msg):\n", " self.msg = msg\n", "\n", " def __str__(self):\n", " return self.msg\n", "\n", "\n", "def say_nick(nick):\n", " if nick == '바보':\n", " raise MyError(\"허용되지 않는 별명입니다.\")\n", " print(nick)\n", "\n", "try:\n", " say_nick(\"천사\")\n", " say_nick(\"바보\")\n", "except MyError as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 05-5 내장 함수" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# abs: 어떤 숫자를 입력 받았을 때, 그 숫자의 절대값을 돌려주는 함수\n", "abs(3)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abs(-3)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.2" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abs(-1.2)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# all: 반복 가능한(iterable), 자료형(리스트, 튜플, 문자열, 딕셔너리, 집합 등) x가 모두 참이면 True, 아니면 False 를 리턴\n", "all([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "all([1, 2, 3, 0])" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# any: x 중 하나라도 참이면 True, x 가 모두 거짓일 경우에민 False 를 리턴, all(x) 의 반대 경우\n", "any([1, 2, 3, 0])" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "any([0, ''])" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# chr: 아스키(ascii) 코드값을 입력받아 그 코드에 해당하는 문자를 출력\n", "chr(97)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chr(48)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__delitem__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__iadd__',\n", " '__imul__',\n", " '__init__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__reversed__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'append',\n", " 'clear',\n", " 'copy',\n", " 'count',\n", " 'extend',\n", " 'index',\n", " 'insert',\n", " 'pop',\n", " 'remove',\n", " 'reverse',\n", " 'sort']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# dir: 객체가 자체적으로 가지고 있는 변수나 함수(메서드)를 출력\n", "dir([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__delitem__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'clear',\n", " 'copy',\n", " 'fromkeys',\n", " 'get',\n", " 'items',\n", " 'keys',\n", " 'pop',\n", " 'popitem',\n", " 'setdefault',\n", " 'update',\n", " 'values']" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir({'1': 'a'})" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 1)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# divmod(a, b): a를 b로 나눈 몫과 나머지를 튜플 형태로 리턴\n", "divmod(7, 3)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(6.0, 0.09999999999999998)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "divmod(1.3, 0.2)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# enumerate: 순서가 있는 자료형(리스트, 튜플, 문자형)을 입력받아 인덱스 값을 포함하는 enumerate 객체를 리턴\n", "enumerate(['body', 'far', 'bar'])" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 body\n", "1 far\n", "2 bar\n" ] } ], "source": [ "for i, name in enumerate(['body', 'far', 'bar']):\n", " print(i, name)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# eval: 실행 가능한 문자열을 입력받아 문자열을 실행한 결과값을 리턴\n", "eval('1+2')" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hia'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval(\"'hi' + 'a'\")" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 1)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval(\"divmod(4, 3)\")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 6]\n" ] } ], "source": [ "# filter: 첫번째 인자로 함수 이름을, 두번째 인자로 앞 함수에 차례로 넘길 반복 가능한 자료형을 넣는다.\n", "# 두번째 인자가 차례로 첫번째 인자인 함수에 입력되어 참인 경우에만 다시 묶어서 반환한다.\n", "\n", "# 양수값만 리턴\n", "def positive(l): \n", " result = [] \n", " for i in l: \n", " if i > 0: \n", " result.append(i) \n", " return result\n", "\n", "print(positive([1,-3,2,0,-5,6]))" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 6]\n" ] } ], "source": [ "# fileter 함수로 구현\n", "def positive(x):\n", " return x > 0\n", "\n", "print(list(filter(positive, [1,-3,2,0,-5,6])))" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 6]\n" ] } ], "source": [ "print(list(filter(lambda x: x>0, [1, -3, 2, 0, -5, 6])))" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0xea'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# hex: 정수를 입력받아 16진수로 변화하여 리턴\n", "hex(234)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0x3'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hex(3)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10055616" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# id(object): 객체를 입력받아 객체의 고유 주소값(레퍼런스)을 리턴\n", "\n", "a = 3\n", "id(3)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10055616" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(a)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10055616" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = a\n", "id(b)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10055648" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(4)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n" ] } ], "source": [ "# input: 사용자 입력을 받는 함수\n", "a = input()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hi\n" ] } ], "source": [ "print(a)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter: hi\n" ] } ], "source": [ "b = input(\"Enter: \")" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# int: 숫자 형태의 문자열이나 소수점이 있는 숫자등을 입력받아 정수를 리턴\n", "int('3')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int(3.4)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 2진수로 표현된 '11'을 10진수로 반환\n", "int('11', 2)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "26" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 16진수로 표현된 '1A'를 10진수로 반환\n", "int('1A', 16)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# isinstance(object, class): 첫 번째 인수로 인스턴스, 두 번째 인수로 클래스 이름을 받는다.\n", "# 입력받은 인스턴스가 그 클래스의 인스턴스인지를 판단하여 참이면 True, 거짓이면 False를 리턴한다.\n", "class Person: pass\n", "\n", "a = Person()\n", "\n", "isinstance(a, Person)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = 3\n", "isinstance(b, Person)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### lambda\n", "\n", "- def와 동일한 역할\n", "- 함수를 한줄로 간결하게 만들 때 사용\n", "- def를 사용해야 할 정도로 복잡하지 않거나 def를 사용할 수 없는 곳에 주로 사용\n", "\n", "> lambda 인수1, 인수2, ... : 인수를 이용한 표현식" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum = lambda a, b: a+b\n", " \n", "sum(3, 4)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[>, >]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myList = [lambda a,b: a+b, lambda a,b: a*b]\n", "myList" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myList[0](3, 4)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myList[1](5, 3)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# len: 입력값의 길이(요소의 전체 개수)를 리턴\n", "len('Python')" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len([1, 'a'])" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['P', 'y', 't', 'h', 'o', 'n']" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# list: 반복 가능한 자료형dmf 입력받아 리스트로 만들어 리턴\n", "list('Python')" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list((1,2,3))" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6, 8]\n" ] } ], "source": [ "# map(f, iterable): 함수(f)와 반복 가능한(iterable) 자료형을 입력으로 받는다. \n", "# map은 입력받은 자료형의 각 요소가 함수 f에 의해 수행된 결과를 묶어서 리턴하는 함수\n", "def two_times(numberList):\n", " result = [ ]\n", " for number in numberList:\n", " result.append(number*2)\n", " return result\n", "\n", "result = two_times([1, 2, 3, 4])\n", "print(result)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 6, 8]" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# map 으로 구현\n", "def two_times(x): return x*2\n", "\n", "list(map(two_times, [1, 2, 3, 4]))" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 6, 8]" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# lambda 함수까지 사용하면\n", "\n", "list(map(lambda x: x*2, [1,2,3,4]))" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# max(iterable): 인수로 반복 가능한 자료형을 입력받아 그 최대값을 리턴\n", "max([1,2,3])" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'y'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max('Python')" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# min(iterable): max 함수와 반대로, 인수로 반복 가능한 자료형을 입력받아 그 최소값을 리턴\n", "min([1,2,3])" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'P'" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min('Python')" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'h'" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min('python')" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0o42'" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# oct(x): 정수 형태의 숫자를 8진수 문자열로 바꾸어 리턴\n", "oct(34)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0o30071'" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "oct(12345)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# open(filename, [mode]): \"파일 이름\"과 \"읽기 방법\"을 입력받아 파일 객체를 리턴하는 함수\n", "# 읽기 방법(mode)이 생략되면 기본값인 읽기 전용 모드(r)로 파일 객체를 만들어 리턴\n", "\n", "# [04-3 파일 읽고 쓰기] 참조" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "97" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# ord(c): 문자의 아스키 코드값을 리턴\n", "# ord 함수는 chr 함수와 반대이다.\n", "ord('a')" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "48" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ord('0')" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# pow(x, y): x의 y 제곱한 결과값을 리턴\n", "pow(2, 4)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "27" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pow(3, 3)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# range([start,] stop [,step]): for문과 함께 자주 사용되는 함수\n", "# 입력받은 숫자에 해당되는 범위의 값을 반복 가능한 객체로 만들어 리턴\n", "\n", "# 인수가 하나일 경우\n", "list(range(5))" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[5, 6, 7, 8, 9]" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 인수가 둘일 경우\n", "list(range(5, 10))" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 3, 5, 7, 9]" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 인수가 셋인 경우\n", "list(range(1, 10, 2))" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(0, -10, -1))" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sorted(iterable): 입력값을 정렬한 후 그 결과를 리스트로 리턴\n", "sorted([3, 1, 2])" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(['a', 'c', 'b'])" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['e', 'o', 'r', 'z']" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(\"zero\")" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted((3, 2, 1))" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "a = [3, 1, 2]\n", "result = a.sort()\n", "print(result)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3'" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# str(object): 문자열 형태로 객체를 변환하여 리턴\n", "str(3)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi'" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str('hi')" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi'" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'hi'" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'HI'" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str('hi'.upper())" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'HI'" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'hi'.upper()" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('a', 'b', 'c')" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# tuple(iterable): 반복 가능한 자료형을 입력받아 튜플 형태로 바꾸어 리턴\n", "tuple('abc')" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tuple([1,2,3])" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tuple((1,2,3))" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# type(object): 입력값의 자료형이 무엇인지 알려주는 함수\n", "type(\"abc\")" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type([ ])" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "_io.TextIOWrapper" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(open(\"test\", 'w'))" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# zip(iterable*): 동일한 개수로 이루어진 자료형을 묶어 주는 역할을 하는 함수\n", "zip([1, 2, 3], [4, 5, 6])" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 4), (2, 5), (3, 6)]" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip([1, 2, 3], [4, 5, 6]))" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 4, 7), (2, 5, 8), (3, 6, 9)]" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('a', 'd'), ('b', 'e'), ('c', 'f')]" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip(\"abc\", \"def\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 05-6 외장함수\n", "\n", "### sys\n", "\n", "- sys 모듈은 파이썬 인터프리터가 제공하는 변수들과 함수들을 직접 제어할 수 있게 해주는 모듈\n", "\n", "#### 명령행에서 인수 전달하기 - sys.argv\n", "\n", "> C:/User/home>python test.py abc pey guido\n", "\n", "- 위와 같이 명령행에서 abc, pey, guido 라는 인수를 전달하면 sys.argv 라는 리스트 변수에 전달된다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing argv_test.py\n" ] } ], "source": [ "%%writefile argv_test.py\n", "import sys\n", "\n", "print(sys.argv)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\r\n", "04-sys1.py\r\n", "04-sys2.py\r\n", "04-새파일.txt\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb\r\n", "05장 파이썬 날개달기.ipynb\r\n", "__pycache__\r\n", "argv_test.py\r\n", "foo.txt\r\n", "game\r\n", "mod1.py\r\n", "test\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['argv_test.py', 'you', 'need', 'Python']\n" ] } ], "source": [ "%run argv_test.py you need Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 강제로 스크립트 종료하기 - sys.exit\n", "\n", "> sys.exit()\n", "\n", "#### 자신이 만든 모듈 불러와 사용하기 - sys.path\n", "\n", "- sys.path 는 파이썬 모듈들이 저장되어 있는 위치를 나타낸다.\n", "- 모듈 저장 위치를 추가하기 위해서는 sys.path.append() 를 사용한다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.4/dist-packages/IPython/extensions', '/root/.ipython']\n" ] } ], "source": [ "import sys\n", "\n", "print(sys.path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### pickle\n", "\n", "- 객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈\n", "- pickle 모듈의 dump 함수를 이용하여 객체를 파일에 저장하고\n", "- load 함수를 이용하여 파일에서 객체를 불러온다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import pickle\n", "\n", "f = open(\"test.txt\", \"wb\")\n", "data = {\"1\": \"python\", \"2\": \"you need\"}\n", "pickle.dump(data, f)\n", "f.close()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\t\t\t __pycache__\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\t argv_test.py\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\t foo.txt\r\n", "04-sys1.py\t\t\t\t\t game\r\n", "04-sys2.py\t\t\t\t\t mod1.py\r\n", "04-새파일.txt\t\t\t\t\t test\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test.txt\r\n", "05장 파이썬 날개달기.ipynb\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "�\u0003}q\r\n" ] } ], "source": [ "!more test.txt" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'2': 'you need', '1': 'python'}\n" ] } ], "source": [ "import pickle\n", "\n", "f = open(\"test.txt\", \"rb\")\n", "data = pickle.load(f)\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### OS 모듈\n", "\n", "- 환경 변수나 디렉터리, 파일 등의 OS 자원을 제어할 수 있게 해주는 모듈\n", "\n", "#### 내 시스템의 환경 변수값을 알고 싶을 때 - os.environ\n", "\n", "- 시스템은 제각기 다른 환경 변수값을 가지고 있는데, os.environ은 현재 시스템의 환경 변수 값들을 보여 준다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "environ({'USER': 'root', 'PAGER': 'cat', 'PS1': '', 'LD_PRELOAD': '/usr/lib/coreutils/libstdbuf.so', 'LOGNAME': 'root', 'SHLVL': '2', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline', 'JPY_PARENT_PID': '441', 'SSH_TTY': '/dev/pts/2', 'SSH_CLIENT': '172.17.0.1 38904 22', 'LANG': 'ko_KR.UTF-8', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:', 'SSH_CONNECTION': '172.17.0.1 38904 172.17.0.13 22', 'HOME': '/root', 'OLDPWD': '/root', 'TERM': 'xterm-color', 'GIT_PAGER': 'cat', 'PATH': '/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games', '_': '/usr/bin/stdbuf', 'SHELL': '/bin/bash', 'CLICOLOR': '1', 'PWD': '/workspace/myNotebook', 'MAIL': '/var/mail/root', '_STDBUF_O': '0'})" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "\n", "os.environ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리턴받은 객체가 딕셔너리이기 때문에 다음과 같이 호출할 수 있다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'path'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0menviron\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"path\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/usr/lib/python3.4/os.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, key)\u001b[0m\n\u001b[1;32m 631\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 632\u001b[0m \u001b[0;31m# raise KeyError with the original key value\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 633\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 634\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdecodevalue\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvalue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 635\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mKeyError\u001b[0m: 'path'" ] } ], "source": [ "os.environ[\"path\"]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.environ['PATH']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 디렉터리 위치 변경하기 - os.chdir\n", "\n", "> os.chdir(\"C:WINDOWS\")\n", "\n", "#### 디렉터리 위치 리턴받기 - os.getcwd\n", "\n", "> os.getcwd()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/workspace/myNotebook/점프 투 파이썬'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.getcwd()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 시스템 명령어 호출하기 - os.system" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.system('dir')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n" ] } ], "source": [ "import os\n", "print(os.system('ls'))" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### 실행한 시스템 명령어의 결과값 리턴받기 - os.popen\n", "\n", "- 시스템 명령어를 실행시킨 결과값을 읽기 모드 파일 객체로 리턴\n", "\n", "> f = os.popen(\"dir\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "f = os.popen(\"ls\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\n", "04-sys1.py\n", "04-sys2.py\n", "04-새파일.txt\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb\n", "05장 파이썬 날개달기.ipynb\n", "__pycache__\n", "argv_test.py\n", "foo.txt\n", "game\n", "mod1.py\n", "test\n", "test.txt\n", "\n" ] } ], "source": [ "print(f.read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 기타 유용한 os 관련 함수\n", "\n", "| 함수 | 설명 |\n", "|:-:|:-:|\n", "| os.mkdir() | 디렉터리 생성 |\n", "| os.rmdir() | 디렉터리 삭제, 단 디렉터리가 비어있어야 함 |\n", "| os.unlink() | 파일을 지운다. |\n", "| os.rename(src, dst) | 파일명 변경 |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### shutil\n", "\n", "- 파일을 복사해 주는 파이썬 모듈\n", "\n", "#### 파일 복사하기 - shutil.copy(src, dst)\n", "\n", "- src 파일을 dst 라는 이름으로 복사\n", "- dst 가 디렉터리라면 dst 디렉터리 안에 src 이름으로 복사\n", "- 동일한 dst 파일이 존재하면 덮어 씀" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\t\t\t __pycache__\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\t argv_test.py\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\t foo.txt\r\n", "04-sys1.py\t\t\t\t\t game\r\n", "04-sys2.py\t\t\t\t\t mod1.py\r\n", "04-새파일.txt\t\t\t\t\t test\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test.txt\r\n", "05장 파이썬 날개달기.ipynb\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "!more foo.txt" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "!more test" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "import sys\r\n", "\r\n", "print(sys.argv)\r\n" ] } ], "source": [ "!more argv_test.py" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'argv_test2.py'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import shutil\n", "shutil.copy(\"argv_test.py\", \"argv_test2.py\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "01장 파이썬이란 무엇인가?.ipynb\t\t\t __pycache__\r\n", "02장 파이썬 프로그래밍의 기초, 자료형.ipynb\t argv_test.py\r\n", "03장 프로그램의 구조를 쌓는다! 제어문.ipynb\t argv_test2.py\r\n", "04-sys1.py\t\t\t\t\t foo.txt\r\n", "04-sys2.py\t\t\t\t\t game\r\n", "04-새파일.txt\t\t\t\t\t mod1.py\r\n", "04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb test\r\n", "05장 파이썬 날개달기.ipynb\t\t\t test.txt\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "import sys\r\n", "\r\n", "print(sys.argv)\r\n" ] } ], "source": [ "!more argv_test2.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### glob\n", "\n", "- 특정 디렉터리 안의 파일 이름 모두를 알아야 할 때 사용하는 모듈\n", "\n", "#### 디렉터리에 있는 파일들을 리스트로 만들기 - glob(pathname)\n", "\n", "- 디렉터리 내의 파일들을 읽어서 리턴\n", "- *, ? 등의 메타 문자 사용 가능" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['./04-sys2.py',\n", " './04장 프로그램의 입력과 출력은 어떻게 해야 할까?.ipynb',\n", " './04-sys1.py',\n", " './04-새파일.txt']" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import glob\n", "\n", "glob.glob(\"./04*\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### tempfile\n", "\n", "- 파일을 임시로 만들어서 사용할 때 유용한 모듈\n", "- mktemp()는 중복되지 않는 임시 파일의 이름을 무작위로 생성해서 리턴\n", "- TemporaryFile()은 임시 저장 공간으로 사용될 파일 객체를 리턴\n", "- 기본적으로 바이너리 쓰기 모드(wb)이며, close()가 호출되면 이 파일 객체는 사라진다." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/tmp/tmp2wexrlak'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import tempfile\n", "filename = tempfile.mktemp()\n", "filename" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<_io.BufferedRandom name=58>\n" ] } ], "source": [ "f = tempfile.TemporaryFile()\n", "print(f)\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### time\n", "\n", "- 시간과 관련된 유용한 함수 포함" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1506492100.01737" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# time.time : 현재 시간을 실수 형태로 리턴, 1970년 1월 1일 기준으로 지난 시간을 초 단위로 리턴\n", "import time\n", "\n", "time.time()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "an integer is required (got type builtin_function_or_method)", "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[0;31m# time.localtime : time.time()에 의해서 반환된 실수값을 이용해서 연도, 월, 일, 시, 분, 초 의 형태로 바꾸어 주는 함수\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlocaltime\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtime\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: an integer is required (got type builtin_function_or_method)" ] } ], "source": [ "# time.localtime : time.time()에 의해서 반환된 실수값을 이용해서 연도, 월, 일, 시, 분, 초 의 형태로 바꾸어 주는 함수\n", "time.localtime(time.time)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "time.struct_time(tm_year=2017, tm_mon=9, tm_mday=27, tm_hour=6, tm_min=2, tm_sec=55, tm_wday=2, tm_yday=270, tm_isdst=0)" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "time.localtime(time.time())" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2017" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "time.localtime(time.time()).tm_year" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Wed Sep 27 06:05:05 2017'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# time.asctime : time.localtime에 의해서 반환된 튜플 형태의 값을 알아보기 쉬운 형태로 리턴\n", "time.asctime(time.localtime(time.time()))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Wed Sep 27 06:05:52 2017'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# time.ctime : 위와 같은 결과이나 항상 현재 시간만을 리턴\n", "time.ctime()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### time.strftime\n", "\n", "> time.strftime('출력할 형식 포맷 코드', time.localtime(time.time()))\n", "\n", "#### 포맷 코드\n", "\n", "| 포맷코드 | 설명 | 예 |\n", "| :-: | :-- | :-: |\n", "| %a | 요일 줄임말 | Mon |\n", "| %A | 요일 | Monday |\n", "| %b | 달 줄임말 | Jan |\n", "| %B | 달 | January |\n", "| %c | 날짜와 시간을 출력함 | 06/01/01 17:22:21 |\n", "| %d | 날(day) | [00, 31] |\n", "| %H | 시간 - 24시간 출력 형태 | [00, 23] |\n", "| %I | 시간 - 12시간 출력 형태 | [01, 12] |\n", "| %j | 1년 중 누적 날짜 | [001, 366] |\n", "| %m | 달 | [01, 12] |\n", "| %M | 분 | [01, 59] |\n", "| %p | AM or PM | AM |\n", "| %S | 초 | [00, 61] |\n", "| %U | 1년 중 누적 주-일요일을 시작으로 | [00, 53] |\n", "| %w | 숫자로 된 요일 | [0(일요일), 6 ]\n", "| %W | 1년 중 누적 주-월요일을 시작으로 | [00, 53] |\n", "| %x | 현재 설정된 로케일에 기반한 날짜 출력 | 06/01/01 |\n", "| %X | 현재 설정된 로케일에 기반한 시간 출력 | 17:22:21 |\n", "| %Y | 년도 출력 | 2001 |\n", "| %Z | 시간대 출력 | 대한민국 표준시 |\n", "| %% | 문자 | % |\n", "| %y | 세기부분을 제외한 년도 출력 | 01" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'09/27/17'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import time\n", "time.strftime('%x', time.localtime(time.time()))" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Wed Sep 27 06:28:49 2017'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "time.strftime('%c', time.localtime(time.time()))" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# time.sleep : 주로 루프 안에서 사용하여 일정한 시간 간격을 두고 루프를 실행\n", "\n", "import time\n", "\n", "for i in range(10):\n", " print(i)\n", " time.sleep(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### calendar\n", "\n", "- 파이썬에서 달력을 볼 수 있게 해주는 모듈" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 2017\n", "\n", " January February March\n", "Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n", " 1 1 2 3 4 5 1 2 3 4 5\n", " 2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12\n", " 9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19\n", "16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26\n", "23 24 25 26 27 28 29 27 28 27 28 29 30 31\n", "30 31\n", "\n", " April May June\n", "Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n", " 1 2 1 2 3 4 5 6 7 1 2 3 4\n", " 3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11\n", "10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18\n", "17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25\n", "24 25 26 27 28 29 30 29 30 31 26 27 28 29 30\n", "\n", " July August September\n", "Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n", " 1 2 1 2 3 4 5 6 1 2 3\n", " 3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n", "10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n", "17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n", "24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30\n", "31\n", "\n", " October November December\n", "Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n", " 1 1 2 3 4 5 1 2 3\n", " 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10\n", " 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17\n", "16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24\n", "23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31\n", "30 31\n", "\n" ] } ], "source": [ "import calendar\n", "print(calendar.calendar(2017)) # calendar.prcal(2017)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " October 2017\n", "Mo Tu We Th Fr Sa Su\n", " 1\n", " 2 3 4 5 6 7 8\n", " 9 10 11 12 13 14 15\n", "16 17 18 19 20 21 22\n", "23 24 25 26 27 28 29\n", "30 31\n", " " ] } ], "source": [ "calendar.prmonth(2017, 10)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calendar.weekday : 그 날짜에 해당하는 요일 정보를 리턴, 0 - 6\n", "calendar.weekday(2017, 9, 27)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(4, 30)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# calendar.monthrange : 입력받은 달의 1일이 무슨 요일인지와 그 달이 며칠까지 있는지를 튜플 형태로 리턴\n", "calendar.monthrange(2017, 9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### random\n", "\n", "- 난수를 발생시키는 모듈" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.33541440698496394" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# random.random : 0.0 에서 1.0 사이의 실수 중에서 난수값을 리턴\n", "import random\n", "random.random()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.6925208291425975" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "random.random()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# random.randint : 주어진 정수 중에서 난수값을 리턴\n", "random.randint(1, 10)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "47" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "random.randint(1, 55)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "4\n", "2\n", "5\n" ] } ], "source": [ "import random\n", "\n", "def random_pop(data):\n", " number = random.randint(0, len(data)-1)\n", " return data.pop(number)\n", "\n", "data = [1, 2, 3, 4, 5]\n", "\n", "\n", "while data:\n", " print(random_pop(data))" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n", "1\n", "5\n", "2\n" ] } ], "source": [ "# random 모듈의 choice 함수를 사용하여 더 직관적으로 표현\n", "\n", "def random_pop(data):\n", " number = random.choice(data)\n", " data.remove(number)\n", " return number\n", "\n", "data = [1, 2, 3, 4, 5]\n", "\n", "while data: print(random_pop(data))" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 3, 5, 1]" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# random.shuffle : 리스트의 항목을 무작위로 섞어주는 함수\n", "data = [1, 2, 3, 4, 5]\n", "random.shuffle(data)\n", "\n", "data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### webbrowser\n", "\n", "- 기본 웹 브라우저가 자동으로 실행되게 하는 모듈\n", "\n", "```\n", "import webbrowser\n", "webbrowser.open(\"http://google.com\")\n", "\n", "webbrowser.open_new(\"http://google.com\")\n", "```" ] } ], "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.4.3" } }, "nbformat": 4, "nbformat_minor": 2 }