Python 정리
- 설치
python에 대한 좋은 레퍼런스 :
http://www.tutorialspoint.com/python/index.htm
퀵 레퍼런스 :
http://www.tutorialspoint.com/python/python_quick_guide.htm
파이썬을 처음 시작하기 적당한 한글 위키북, 점프 투 파이썬:
- 문법(C++ 베이스로 설명)
모든 statement는 indent로 구분. 함수나 루프, 클래스등은 블럭구분을 위해 {}가 사용되지
않으며, 라인의 끝에 ‘;’ 같은 것도 사용하지 않는다. 블럭에는 시작 라인에만 ‘:’가 사용된다.
* operator : http://www.tutorialspoint.com/python/python_basic_operators.htm ‘++’, ‘–‘ 연산자는 없다.
* 5 data types : Numbers, String, List, Tuple, Dictionary
– Numbers : int, long, float, complex
* variable : 선언이나 정의가 특별히 없다.
* boolean operator : and, or, not
* String quatation : single quatation 과 double quatation 차이가 없다. PHP의 경우, variable expanding이 double quatation에서는 일어나고 single quatation에서는 일어나지 않는다. PHP는 variable 구분자 ‘$’ 를 사용하지만, Python은 구분자가 없는 차이가 아닐까 생각해본다. 다음과 같이 사용한 quatation과 다른 quatation의 경우 ‘\’없이 사용가능하다.
print ("test string 'whooooo~'") print ('test string "whaaaaa~"')
* tuple : immutable list. (item1, item2, …) 와 같이 괄호를 사용. 값이 하나인 tuple은 ‘,’를
적어줘야 한다. (item1,) 과 같이.
* list : mutable. [item1, item2, …] 와 같이 대괄호 사용
* list comprehension : 기존 리스트에서 새로운 리스트 생성을 쉽게 하는 방법.
new_list = [item for in old_list if item…]
for문을 이용해서 리스트 아이템을 구성하고, if문으로 필터링을 할 수 있다.
* dictionary : C++에서 STL Map과 같은 녀석. 키와 밸류의 쌍으로 구성. {“key1″:”value1”,
“key2″:”value2”, …} 와 같이 {} 괄호 사용.
* String formatting : sprintf와 같은 방식이 사용되나, 다음과 같이 % 가 구분자로 이용됨.
print (“%s is not %s”%(“value1”, “value2”))
* if 문 : 조건문에 괄호가 사용되지 않는다.
if a < b : print ("a < b") elif a < c : print ("a < c") else: print("else")
switch-case 문이 파이썬에는 없기 때문에, if-elif-else로 구현되어야 한다.
* for 문
C++에서 사용하는 for 문과는 형식이 다르다.
#for item in tuple or list for item in range(20) print (item)
* while 문
while a < b :
print (a)
a+=1
* 함수 : ‘def’로 함수를 정의(define)한다.
http://www.tutorialspoint.com/python/python_functions.htm
파이썬에서 모든 argument는 reference로 넘겨진다.
def functionname( parameters ): "function_docstring" function_suite return [expression]
기본 사용
def myFun(arg1): "function example" print (arg1) return
파라미터 개수 무제한으로 넘기기
def testFunction(*args): "doc string..." print ("It's a test function! :") for item in args: print (item + "\n") return
* pass : Python에서는 함수나 클래스 정의를 안해도 에러가 나지 않도록 할 수 있다. 바로 “pass”를 사용하는 것. TDD로 접근시, 유용하게 사용할 수 있다.
def emptyFunc(arg1): pass
* 모듈
*Exception : try – except
try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close()
* 클래스 : ‘class’ 를 사용한다.
– __init__(self) : 생성자
– ‘self’ : 자기 자신을 가리키는 참조 인자
class Parent(): pass class MyClass(Parent): def __init__(self): pass
– built-in 속성 : __name__, __doc__, __module__, __dict__
__name__ : class name __doc__ : class documentation string. __module__ : module name which class is defined __dict__ : 클래스 내부의 dictionary. 메소드, 프로퍼티등을 키로 갖게된다. __bases : 베이스 클래스
– 가베지 콜렉션에 의해 참조되지 않는 객체들의 메모리 회수.
– overriding : 연산자도 오버라이딩이 가능하다. 당연하지만…
class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b)
– overloading : 인자 타입을 명시 할 수는 없으므로 인자 개수가 다른 메소드로만 오버로딩 가능
– private property : prefix로 underscore를 __privateProperty = 0 처럼 두번 넣어주면 된다. 물론 완벽한 데이터 하이딩은 아니며 파이썬 내부적으로 클래스 이름을 포함하도록 프로퍼티 명을 변경한다고 한다.
* 입출력
1) 콘솔 : input(), print()
2) 파일 file = open(), file.close(), file.write(), file.read(), file.readline(), etc.
이슈 1 : 함수의 콜 바이 레퍼런스는 어떻게 하는가?
함수 인자가 mutable이냐, unmutable이냐에 따라 달라진다. 리스트나 클래스는 mutable이며 스트링은 unmutable이다. 콜바이 레퍼런스를 쓰고 싶으면 mutable을 쓰고 아니라면 리턴값을 적절히 처리하도록 한다.
이슈2 : 파일 오픈과 같은 경우, 예외처리는 어떻게 하는가?
이슈3 : 로깅과 디버깅은 어떻게 하는가?
익혀야할 표준 모듈 :
– 시간, 입출력, 시스템, 또 뭐가 있을까?
Excercise :
- 기타