본문 바로가기

반응형

Python

(23)
Pickle 모듈 Pickle - python 코드 내에서 파일을 만들고 저장하며 불러올 수 있다. - 일반 텍스트를 파일로 저장할 때는 파일 입출력을 이용한다. 하지만 List나 Class와 같은 텍스트가 아닌 자료형은 일반적인 파일 입출력 방법으로는 데이터를 저장하거나 불러올 수 없다. 파이썬에서는 이와 같은 텍스트 이외의 자료형을 파일로 저장하기 위해 pickle이라는 라이브러리를 제공한다. - python serialization module * 객체를 다시 해당 객체로 변환이 가능한 문자열(byte)로 변환 * 네트워크로 전송 혹은 파일에 저장하기 위해 사용 (객체 자체를 네트워크, 파일에 저장 할 수 없기 때문에) - https://docs.python.org/2/library/pickle.html - dump..
Decorator_03 (Decorator Chaining, Method decoration, Decorator with parameters) Decorator Chaining - 복수개의 decorator 적용 가능 - decorated 된 순서가 중요 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 def star(fn): def wrapper(*args, **kwargs): print('function is decorated with **star**') return fn(*args, **kwargs) return wrapper def at(fn): def wrapper(*args, **kwargs): print('function is decorated with @@at@@') return fn(*args, ..
Decorator_02 (파라미터가 있는 함수 decorator & 모든 함수에 대한 decorator) Decorator - 기존 함수에 기능을 추가하여 새로운 함수를 만듬 - Closure function을 활용 - https://www.python.org/dev/peps/pep-0318/ - decorator 사용 이유는? 함수 혹은 메쏘드에 새로운 기능을 추가하기 위해! - 그렇다면 왜 소스 코드를 수정하지 않는가? 여러 함수에 동일한 기능을 추가할 수 있다. 예를 들면, 모든 함수에 전달된 파라미터의 유효성 검사가 필요하다고 가정했을때, 유효성 검사 코드가 각 함수마다 복사되면 수정의 어려움이 존재한다. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # decorator 함수 정의 def decorate_func(fu..
Decorator_01 (Nested function, Closure) python에서의 함수 파이썬에서 함수는 1st citizen이다. 즉, 객체로 존재한다. 객체이기 때문에 변수 대입, 함수 파라미터 전달 등이 가능하다. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def hello(): print('This is hello function') # 함수를 변수에 대입 hi = hello print(type(hi)) print(hi) hi() ==================================== This is hello function cs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 def hello(word_parameter): print('This is from hello function') ..
Class] 2. 정보은닉(private, protected, public) - c++, java 등의 기타 OOP 언어와는 달리, 파이썬의 경우 restricted한 제한자 적용을 할 수 없음- 파이썬에서의 모든 속성, 메소드는 기본적으로 public- 즉, 클래스의 외부에서 속성, 메소드에 접근이 가능 (사용가능) 123456789101112131415161718192021222324252627282930313233class Bottle: def __init__(self, quantity): self.quantity = quantity def fill(self, quantity): self.quantity = quantity def empty(self): self.quantity = 0 def show(self): print '{}ml inside the bottle'.for..
Class] 1. __init__ & method Class다루고자 하는 데이터(변수)와 데이터를 다루는 연산(함수)를 하나로 캡슐화(encapsulation)하여 클래스로 표현 Object- 클래스로 생성되어 구체화 된 객체(인스턴스)- 실제로 class가 인스턴스화 되어 메모리에 상주하는 상태를 의미- class가 빵틀이라면 object는 실제로 빵틀로 찍어낸 빵이라고 비유 가능 __init__(self)- 생성자함수- 객체가 생성될 때 자동적을 호출되는 초기화 메소드- 객체가 생성될 때 객체를 기본값으로 초기화하는 특수한 메소드 1234567891011121314class Person(object): def __init__(self, name, age): self.name = name self.age = age s1 = Person('tina', ..
1. Series Series ## size : 개수반환## unique : 유일한 값만 ndarray로 반환## count : NaN을 제외한 개수를 반환## value_counts : NaN을 제외하고 각 값들의 빈도를 반환123456789101112131415161718192021222324252627282930import pandas as pdimport numpy as np s = pd.Series([0, 1, 1, 2, 3, 4, 5, 6, 7, np.nan])print s print "len(s) =", len(s)print "s.size =", s.sizeprint "s.shape =", s.shapeprint "s.count =", s.count()print "s.unique =", s.unique() 0..
Day5) 4. import/from import import/from import 12345678import numpy # 모듈 임포트print numpy.random.randint(100)print numpy.random.rand() 110.217166633521cs 123456789import numpy as np # 모듈 임포트 후 alias(별명) 붙임 ## np로 지정했기 때문에 numpy로 사용하지 못한다. np로 사용해야함print np.random.randint(100)np.random.rand() 65Out[60]: 0.05404130204258906cs 12345678910111213from numpy import random as rd print random.randint(100) ----------------------------..