-
Python 기본 문법 공부Python 2021. 11. 8. 02:05
1.
# 문자열 # 문자열 포맷팅 result = 3 + 5 print(result) # 문자열 결합 print("py" "thon") print("py" + "thon") print("py" * 3) # multiline -> """str""" or '''str''' str = """ Life is too short You need python """ strr = ''' str str ''' ### # 문자열 포맷팅 # 1. %-formatting 2. {}-formatting 3.f-String ### "%f" % 3.14 "My name is {}".format("예진") name= "예진" f"My name is {name}" print(str) print(strr) # help 도움말 및 설명 help(len) ### # 파이썬 배열종류 -> list, tuple, dict, set 차이 # 타입이 서로 다른 임의 값 모두 가능 ### # list -> [] 순서O 파이썬 임의 객체 집합 vlist = [1,3,5,7,9] print(vlist, type(vlist)) # tuple -> () 순서O, 초기화 후 내용변경X vtuple = ("ham", "spam") print(vtuple, type(vtuple)) # dict -> {key:value} 순서X vdict = {"ham":4, "spam":5} print(vdict, type(vdict)) # set -> {} 순서X 중복허용X 집합처리에 유용 vset = {1,2,3,4,4} print(vset, type(vset)) # {1,2,3,4} ### # 인덱싱 # 0부터 시작, - 는 거꾸로, 뒤는 -1부터, : 는 슬라이싱 ### vstr = "python is Wonderful" # 0 ~ 17, -18 ~ -1 print(vstr, vstr[0], vstr[-1]) print(vstr[-2], vstr[-8:]) #u onderful print(vstr[:-7]) #python is Wo2.
### 210518_1.py # 1. 자료형(list, set tuple, dict, bool) # 2. 생성자를 통한 형변환 # 3. 깊은 복사 & 얕은 복사 : call by object reference # 4. 연산자(산술, 논리, 관계, 비트) ### # list # append, remove, count, index, sort ### colors = ["red", "green", "blue"] colors.append("blue") # 뒤에추가 ['red', 'green', 'blue', 'blue'] colors.insert(1, "black") # 원하는 위치지정 ['red', 'black', 'green', 'blue', 'black'] colors += ["red"] # 추가는 append를 권장 ['red', 'black', 'green', 'blue', 'black', 'red'] colors += "red" # 'r', 'e', 'd' 각자 추가됨 ['red', 'black', 'green', 'blue', 'black', 'r', 'e', 'd'] colors.count("red") # 해당 원소 개수 세기 len(colors) # 길이 구하는 함수 print(colors) # ['red', 'black', 'green', 'blue', 'black', 'r', 'e', 'd'] print(colors.index("red")) # 원소의 인덱스 찾기 0 print(colors.index("blue")) # 여러개 있으면 앞에것만 출력 3 colors.index("red", 1) # red는 0에 위치하므로 1 위치부터 찾으면 ValueError colors.pop() # 맨 뒤 삭제 colors.pop(1) # black 삭제 print(colors) # ['red', 'green', 'blue', 'blue', 'red', 'r', 'e'] del colors[2] # del 함수를 통한 삭제 ['red', 'green', 'blue', 'red', 'r', 'e'] print(colors) colors.remove("blue") # 해당 원소 삭제. 삭제는 remove 권장 colors.extend(["blue", "yelow", "white"]) # 리스트 확장. 인자로 list만 받음. colors += [] 와 동일 colors.sort() # 정렬 colors.reverse() # 순서 뒤집음 ### # set # 집합연산용, 자료 순서X, 원소 값 중복 허용X ### a = {1,2,3,3} # {1,2,3} b = {3,4,4,5} # {3,4,5} a.union(b) # {1,2,3,4,5} 합집합 a.intersection(b) # {3} 교집합 a.difference(b) # {1,2} 차집합 print(a | b) # {1,2,3,4,5} set 는 연산자로 연산가능 print(a & b) # {3} print(a - b) # {1,2} ### # tuple # 읽기전용, 제공되는 메서드는 적지만 list보다 속도빠름 ### t = (1,2,3) def calc(a,b): # 함수에서 두개 이상의 값을 리턴 하는 경우 tuple로 반환됨 return a+b, a*b x,y = calc(5,4) # 스프레드됨 x = 9, y = 20 print("id:%s, name: %s" % ("kim", "김유신")) # 문자열 포맷팅 args = (3,4) print(calc(*args)) # (7, 12) 반환 ### # 생성자를 통한 형변환 # 인자는 iterable한 지료형이 온다 ### a = set((1,2,3)) # tuple -> set print(a, type(a)) a = set([1,2,3]) # list -> set print(a, type(a)) a = tuple({1,2,3}) # set -> tuple print(a, type(a)) b = list(a) # tuple -> list print(b, type(b)) ### # dictionary # Mapping형. key:value쌍으로 이루어짐. 자료의 순서가 없음. 빠른검색이 필요할때 사용 ### d = dict(a=1, b=2, c=3) color = {"apple" : "red", "banana" : "yellow"} color["cherry"] = "red" # 값 추가 #color['apple', 'banana'] # 컬럼 2개이상 조회불가 for item in color.items(): print(item, type(item)) # tuple for k,v in color.items(): print(k,v) print(color.keys(), color.values(), type(color.keys()), type(color.values())) # dict_keys, dict_values 클래스 "cherry" in color # True del color["cherry"] # 삭제 "cherry" in color # False "cherry" not in color # True color.clear() # 전체 초기화 {} phone = {"kim":"1111", "lee":"2222", "park":"3333"} p = phone # 주소가 복사된다 id(p), id(phone) # id가 같다(메모리 주소) help(id) ### # Bool 형 # True, False # 0 = False, 0 을 제외한 수 = True # None, "", 0, 0.0 [], {}, () => False # 빈문자열, 빈객체는 False ### 1 < 2, 1 !=2, 1==2 # (True, True, False) bool(0) # False bool(-1) # True bool(1) # True bool("") # False bool("demo") # True bool(None) # False 파이썬은 null대신 None 쓰고 약속어 첫글자 대문자씀 ### # 얕은 복사와 깊은 복사 # 기본 할당은 얕은 복사(같은 메모리 할당)로 됨 # 파이썬은 Value Type이 없고 무조건 Reference Type (자바와 비슷) # 값을 '참조' 하기때문에 복사시 주의 # 자바는 call by reference 지만 python은 call by object reference # 파이썬도 가비지콜렉터가 있음 # 변수는 값에 대한 reference를 가짐(pointer 비슷) # 숫자데이터형, tuple, 문자열 -> immutable 불변형 # list, dict -> mutable 가변형 # 데이터형 중 immutable 변수형은 새 값에 대해 새주소를 만들지만 # mutable한 변수형은 내용을 바꾸면 되므로 새 값 새주소를 만들 필요X ### x = 5 # immutable 불변형 y = x # 얕은 복사 (a와 b는 같은 값을 참조) print(x, y) id(x), id(y) # id가 같다 x = 10 # x 값 변경시 새 값을 만들고 그에 대해 x는 해당 메모리가 할당됨 print(x, y) id(x), id(y) # id 값이 달라짐 sca = [1,2,3] # mutable 가변형 scb = a # 얕은 복사 (a와 b는 같은 메모리를 참조) id(sca), id(scb) # id 가 같다 sca[0] = 10 print(sca, scb) # b의 값도 변경되었음 id(sca), id(scb) # id 가 같다 dca = [1,2,3] dcb = dca[:] # 깊은 복사 (b에 a값을 복사하였지만 다른 메모리 할당) id(dca), id(dcb) # id가 다르다 dca[0] = 38 print(dca, dcb) import copy # 일반적인 경우는 copy 모듈 사용 a = [1,2,3] b = copy.deepcopy(a) # 깊은 복사 a, b id(a), id(b) ### # 연산자 # 산술, 관계, 논리, 비트 ### # 산술 연산자 2**3 # 8 5%2 # 1 5/2.0 # 2.5 5/2 # 2.5 4/2 # 2.0 실수값 리턴 5//2 # 2 정수값 리턴 # 관계 연산자 5 == 6 # False 5 != 6 # True 1 > 3 # False 4 <= 5 # True # 논리 연산자 (&& || ! 기호가 아닌 단어로 사용) True and False, False and False, True and True # False, False, True True or False, False or False, True or True # True, False, True3.
### 210518_2.py # 분기문 # 반복문 # list comprehensions # filter 함수 # 파이썬 데이터 형식 : mutable, immutable # 함수 인자 전달(call by object reference) & 스코핑 룰 Local-Global-Built in ### # 분기문 # if-elif-else # switch 없었는데 3.10 버전에 추가됨 # 파이썬은 약식이 많다 ### score = int(input("Input Score: ")) if 90 <= score <= 100: grade = "A" elif 80 <= score < 90: grade = "B" elif 70 <= score <= 80: grade = "C" elif 60 <= score < 70: grade = "D" else: grade = "F" print("Grade is " + grade) ### # 반복 구문 # while-else (else 거의안씀) # for-in-else ### # while value = 5 while value > 0: print(value) value -=1 # for-in lst = ["apple", 3, 4.0] for item in lst: print(item, type(item)) # 구구단 # for-in문을 for루프문처럼 사용하기 : range() 함수 이용 for i in range(2,6): print("--{0} 단--".format(i)) # 문자열 포맷팅 for j in range(1,10): print("{0} * {1} = {2}".format(i, j, i*j)) list(range(1,20)) list(range(1,20,3)) # continue lst = [1,2,3,4,5,6,7,8,9,10] for item in lst: if item % 2 == 0: continue print("item : {0}".format(item)) ### # list comprehensions 리스트 내포(함축) ### lst = [1,2,3,4,5] [1**2 for i in lst] test=("apple", "banana", "orange") [len(i) for i in test] d = {100 : "apple", 200 : "banana", 300 : "orange"} [v.upper() for v in d.values()] # filter 함수 # filter(<function | None, <이터레이션이 가능한 자료형>) funcion에 조건식 lst = [10,25,30] iterL = filter(None, lst) # None 정하면 인자 그대로 할당 for item in iterL: print("item : {0}".format(item)) id(iterL), id(lst) # 다른 객체 def getBiggerThan20(i): return i > 20 # 관계 연산자(bool형 반환) lst = [10,25,30] iterL = filter(getBiggerThan20, lst) # 함수로 filter 조건 지정 for item in iterL: print("item : {0}".format(item)) # lamda 활용 f = filter(lambda x:x%2 == 0, lst) # lambda 조건식이 True인 걸 반환 for item in f: print("item : {0}".format(item)) ### # 함수 ### # 간단한 페이징 계산 함수 def getTotalPage(m, n): return m // n + 1 if m % n != 0 else m // n print(getTotalPage(5, 10)) # 1 출력 print(getTotalPage(10, 10)) # 1 출력 print(getTotalPage(15, 10)) # 2 출력 print(getTotalPage(25, 10)) # 3 출력 print(getTotalPage(30, 10)) # 3 출력 globals() # 전역 변수 출력 ### # 프로그램 메모리 영역 # 코드 영역-데이터 영역-힙 영역-스택 영역 # 코드 영역 : 프로그램 코드 # 데이터 영역 : 전역(global), 정적(static) 변수 # heap : 동적 메모리 공간 (런타임에 크기결정) # stack : 지역(local), 매개(parameter) 변수 (컴파일타임에 크기결정) ### ### # 파이썬 데이터 형식 # 가변형(mutable), 불변형(immutable) # 숫자 데이터형(int, float, complex), 문자열, tuple -> 불변형 # list, dict -> 가변형 # 인자를 넘길때 변수의 reference가 아닌 변수가 담고있는 data에 대한 reference를 넘김 # python은 call by object reference # 새로운 값 -> 새로운 주소 할당 # 자료가 mutable하면 call by reference로 보임 immutable하면 call by value로 보임 ### def intersect(prelist, postlist): retlist = [] for x in prelist: if x in postlist and x not in retlist: retlist.append(x) return retlist intersect("HAAM", "SPAM") # ['A', 'M'] 반환 # python Closure 함수 # 함수 상위 stack 영역 데이터의 변수(함수 정의될 당시 상위 블럭)는 내부 함수에서 사용 가능 # 하위 stack 데이터는 사용 불가 def say_words(msg): str = "안녕? 이걸 출력해줘! : {}" def say_sentence(): # closure 함수(블록 내 지역변수값을 기억함) return str.format(msg) return say_sentence a = say_words("출출하다") print("a는 무엇일까? : ", a) a() # 인자 전달(얕은 복사) : mutable한 변수는 참조가 복사되므로 실제 값이 변경된다 wordlist=["J", "A", "M"] def change(x): x[0] = "H" change(wordlist) wordlist # ['j', 'A', 'M'] # 인자 전달(깊은 복사) wordlist=["J", "A", "M"] def change(x): x = x[:] x[0] = "H" change(wordlist) wordlist # ['J', 'A', 'M'] ### # 스코핑 룰 # LGB (Local - Global - Built in) # 이름 충돌시 이름공간에 대해 위의 우선순위 적용 ### #함수 내부에서 전역 변수 사용 x = 1 def func(a): return x + a # 전역 변수 x를 찾아서 사용 # 함수 내부에서 지역 변수 선언 x = 1 id(x) def func2(a): x = 2 # 지역 변수 x가 생성됨 (js에서는 var나 let 키워드 선언 안하면 전역 변수로 취급하지만 파이썬은 형식선언이 없어서 이렇게 써도 지역변수임) print(id(x)) # 전역 변수 x와 다른 객체 return x + a # 함수 내부 지역 변수 x를 찾아서 사용 print(x, func2(x), x, id(x)) # 전역 변수 x값은 변하지 않았음 # global 키워드로 local 블럭에서 전역 변수 선언 # 전역 영역의 immutable 형식을 지역 영역 변수에서 사용하고 싶을 경우 사용 g = 1 h = g def testScope(a): global g # 전역 변수 g를 가리킴 g = 2 # global 키워드 지정해 전역 영역에 존재하는 변수 값을 변경 print(id(g)) return g + a print(g, id(g), testScope(1), g, id(g), h) # 함수 내부에서 지역 변수 선언 g = [1,2,3] h = g print(g, h, id(g), id(h)) def testScope(a): g = [1,2,4] # 지역 변수 g가 선언되고 전역 변수 g의 값은 변경되지 않음 print(id(g)) return g[2] + a print(g, id(g), testScope(1), g, id(g), h) # 함수 내부에서 mutable한 전역 변수 참조 g = [1,2,3] h = g print(g,h,id(g), id(h)) def testScope(a): g[2] = 4 # 가변인자는 reference를 참조하기 때문에 global키워드 없이 해당 변수값 변경 가능 print(id(g)) # 전역 변수 g를 참조 return g[2] + a print(g, id(g), testScope(1), g, id(g), h) # 함수 내부에서 immutable한 전역 변수 참조 g = 3 h = g print(g,h,id(g), id(h)) def testScope(a): print(id(a)) # 값 변경 전에는 g와 h와 매개변수 a는 같은 객체 a = 4 # immutable 한 자료는 값변경시 다른 객체가됨 print(id(a)) return 4 print(g, id(g), testScope(g), g, id(g), h) #g와 h 객체 값은 변경되지 않았음 ### #*컴파일되는 언어:C, C++, C#, VB # 소스코드(*.c) ---------> 기계어 코드(*.exe) # 빌드, 만들기, 컴파일 # 책을 번역해야 접근이 가능한 경우 # 정적인 형식으로 확장이 안됨 # # *인터프리터(라인단위로 해석)언어:Python, JavaScript # 소스코드(*.py) 행단위로 해석되고 실행된다. # # 통역으로 비유 # 동적인 형식으로 확장이 된다. ### # swap 하기 # 여러 값을 반환할때 tuple로 반환 (,로 이으면 tuple형 됨) def swap(x,y): return y,x x, y = 10,20 x, y x, y = swap(x, y) x, y4.
### 210520.py # 함수 인자 전달 방식 : 인자 기본값, 키워드 인자, 가변 인자(*), 미정의 인자(**) # * 키워드 : 스프레드(js ... 키워드와와 비슷하다. tuple로 반환) # 람다 함수 # pass 키워드 # help() 함수와 __doc__ 속성 # 이터레이터 & 제너레이터 # 클래스 & namespace # 함수 파라미터 기본값 설정 def times(a=10, b=20): return a*b # 키워드 인자 : 파라미터 지정해서 인자 넘기는거 def connectURI(server, port): str = "http://" + server + ":" + port return str connectURI("credu.com", "8080") connectURI(port="80", server="test.com") # 파라미터 지정시 순서상관 없이 전달가능 # 가변 인자 : * 키워드(애스터리스크) (tuple로 스프레드) def union(*ar): # * 키워드 : js의 ... 키워드와 같이 가변 인자를 스프레드한다(tuple 형으로 받음) result = [] for item in ar: for x in item: if x not in result: result.append(x) return result union("HAAM", "EGG") union("HAAM", "EGG", "SPAM") # * 키워드 x = [1,2,3,4] y = [5,6,7] za = [*x, *y] # 1차원으로 스프레드 za zb = [x,y] # 2차원 list zb # 정의되지 않은 인자 처리 : ** 키워드 (dictionary로 스프레드) # 옵션처리시 유용. dict 형으로 받는다. def userURIBuilder(server, port, **user): str = "http://" + server + ":" + port + "/?" for key in user.keys(): str += key + "=" + user[key] + "&" # Query String 처리 str = str[:-2] return str print(userURIBuilder("test.com", "8080", id="kim", passwd="1234", name="mike", age="30")) ### 람다 함수 # js 익명, 화살표 함수, swift 클로져와 같다 # 객체만 존재하는 익명함수 ### g = lambda x,y:x*y g(2,3) (lambda x:x*3)(3) # 일회성 함수 globals() # 전역 객체 확인 (위의 일회성 함수는 메모리에 없음) # pass 키워드 : 아무 일도 하지 않는 코드 작성시 # while True: # pass class Temp: pass ### __doc__ 속성, help 함수 : 도움말 보기 & 추가 # 함수 원형 파라미터를 볼수있으므로 자주 활용할것 ### help(print) print.__doc__ def add(a,b): """이 함수는 2개의 숫자를 입력받아서 덧셈을 리턴하는 함수입니다.""" return a+b help(add) ### 이터레이터 # list, tuple, string 같은 시퀀스 형식(순회 가능한 객체)은 iterator 객체가 포함됨 ### s = "abc" it = iter(s) it next(it) # 'a' next(it) # 'b' for char in "gold": # 문자열도 시퀀스형임 print(char) # return의 한계 # 함수 의도 : 문자열의 문자를 1개씩 반환하기 -> return으로 불가 => yield 키워드 사용 def getChar(): data = "abc" for char in data: return char it = iter(getChar()) next(it) # 'a' next(it) # 에러 (StopIteration) ### 제너레이터 : yield 키워드 # 이터레이터를 생성하는 함수. # 함수 안에서 yield 키워드 사용하면 해당 함수는 제너레이터가 된다 # 원형 : <yield 값> -> 값을 추출하고 추출이 끝나면 함수 종료 ### def numberGenerator(): yield 0 yield 1 yield 2 for i in numberGenerator(): print(i) n = numberGenerator() n # generator object next(n) # '0' n.__next__() # '1' __next__ : next() 같은 기능 n.__next__() # '2' def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] # generator 객체 반환 for char in reverse("gold"): print(char) ### 클래스 # Object Oriented Programming # 추상성, 상속성, 다형성 # 파이썬은 캡슐화(정보 은닉)가 약하다 # 클래스의 모든 메소드는 첫번째 파라미터로 클래스 자신에 대한 참조 객체가 온다 # 관용적으로 self라 명칭한다 # 클래스 namespace, 인스턴스 namespace 구분 # 기본 접근 권한은 public # 파이썬은 함수기반 & 클래스 기반 하이브리드 언어 ### class Person: sayHello ="Hello" # 클래스 원본 멤버 변수 (보통 공통데이터) (다른 언어의 static 멤버) id = 0 def __init__(self): self.name = "박예진" # 인스턴스 멤버 변수 Person.id += 1 # 클래스 멤버 변수는 값이 기억되므로 축적됨 def print(self): print(f"My name is {self.name}, {self.sayHello}") p1 = Person() p1.print() p2 = Person() p2.name = "김예진" p2.print() # 인스턴스 객체 영역 => 클래스 객체 영역 => 전역 영역 순으로 namespace 접근 p2.sayHello = "Hello!" # 해당 인스턴스 namespace에 sayHello가 정의됨 Person.sayHello # 클래스 멤버 변수 값은 그대로 p1.__class__.sayHello p2.__class__.sayHello p1.print() p2.print() p2.__class__.sayHello = "Hello!!" # 클래스에 직접 접근하여 변경하면 전체 객체에 영향 Person.sayHello # 바뀐 값 p2.sayHello # 인스턴스 레벨의 sayHello 접근(override) p1.sayHello # sayHello 객체 멤버가 없으므로 클래스 레벨의 sayHello 접근 # 동적 형식 언어 # 런타임에 클래스 및 인스턴스 namespace에 멤버 변수 추가삭제 가능(인터프리터 특징) # 런타임(실행중)-컴파일타임(스크립트언어는없음)-디자인타임(코딩중) # 권장하지 않는 코딩방식(오타쳐서 의도하지 않은 결과 발생 가능성) Person.title = "new title" # 이런식으로 새로 값을 할당하지 말것 p1.title p2.title print(f"인스턴스 갯수 : {Person.id}") p1.age = 24 p1.age #p2.age # Attribute Error : p2 namespace 에는 age 속성이 없음 # self 키워드가 누락되면 전역 변수와 겹칠 수 있다. str = "Not Class Member" class GString: def __init__(self): self.str = "" def set(self, msg): self.str = msg def print(self): print(str) # 의도하지 않은 결과 발생 g = GString() g.set("First Message") g.print() # 인스턴스가 해당 클래스로 생성됐는지 확인 # python 3 이후로 암묵적으로 object 객체 상속(__init__, __del__, __add__ 등 중요 멤버들이 정의되어있음) isinstance(p1, Person) isinstance(g, Person) isinstance(p1, object) ### 생성자 소멸자 메서드 # 소멸자는 인스턴스 객체의 레퍼런스 카운트가 0이 될 때 호출된다. class MyClass: def __init__(self, value): # 생성자 self.value = value print("Instance is created! value=", value) def __del__(self): #소멸자 print("Instance is deleted!") d = MyClass(5) del d # 소멸자 호출(굳이 안해도 gc가 수거함) ### 정적 메서드 & 클래스 메서드 (둘이 호출은 비슷하지만 파라미터 및 상속 여부에서 차이남) # 정적 메서드 : 클래스를 통해 직접 호출. 인스턴스 생성 없이 호출가능. 상속 불가 # 메서드 정의시 self 선언X. self있으면 -> 인스턴스 메서드 class MyCalc(object): @staticmethod # 메타 태그(데코레이터) (없어도 되지만 명시) def my_add(x,y): return x+y a = MyCalc.my_add(5,7) a # 클래스 메서드 : 클래스 자체에 작용하는 메서드. 상속 가능 # 첫 인자로 클래스 객체가 전달된다. 관용적으로 cls 라 명칭 class CoeffVar(object): coefficient = 1 @classmethod def mul(cls, fact): return cls.coefficient * fact class MulFive(CoeffVar): #상속 coefficient = 5 x = MulFive.mul(4) print(x) # private 멤버 속성 # 멤버 명칭이 __로 시작하는 경우 외부에서 참조할때 '_클래스이름__멤버이름'으로 자동 변경 # __*__ : 식별자의 앞뒤에 __가 붙어있는 경우는 시스템에서 정의한 이름 (언어 수준) # __* : 클래스 안에서 외부로 노출되지 않는 식별자로 인식 class BankAccount: def __init__(self, id, name, balance): self.__id = id self.__name = name self.__balance = balance def deposit(self, amount): self.__balance += amount def withdraw(self, amount): self.__balance -= amount def __str__(self): # print 등 문자열을 요구하면 자동 호출(다른 언어의 toString() 메서드) return "{0}, {1}, {2}".format(self.__id, self.__name, self.__balance) account1 = BankAccount(100, '박예진', 15000) account1.withdraw(3000) print(account1) print(account1.__balance) # 외부에서 접근시 AttributeError # 클래스 외부에서 private 멤버 변수 접근 (테스트 용도의 백도어) print(account1._BankAccount__balance) # 언어 한계 ### 연산자 오버로딩 (연산자 의미 추가) # 미리 정의된 수치 연산자를 오버로딩하여 인스턴스간 연산을 가능하게한다. # 연산자가 메서드로 미리 정의되어있음. 해당 메서드를 오버로딩 class NumBox: def __init__(self, num): self.Num = num def __add__(self, num): # + 연산자 self.Num += num def __sub__(self, num): # - 연산자 self.Num -= num n = NumBox(40) n + 100 print(n.Num) n - 110 print(n.Num) # python은 정식으로 메서드 오버로딩을 지원하지 않는다.5.
### 210521.py # 상속 # 다중상속 # 모듈과 패키지 # 파일 입출력 # 예외 처리 ### # 상속 # pyhon 객체는 dict 형식(js와 비슷) -> __dict__ 속성으로 확인 # 클래스 상속과 이름공간 # 인스턴스 객체 영역 -> 클래스 객체 영역 -> 전역 영역 # 인스턴스 객체 영역 -> 클래스 객체간 상속을 통한 영역(자식 -> 부모) -> 전역 영역 # 인스턴스 생성해도 Attribute만 namespace에 할당하고 메서드는 클래스에서 참조하여 메모리를 아낌 ### class Person: def __init__(self, name, phoneNumber): self.name = name self.phoneNumber = phoneNumber def printInfo(self): print("Info(Name:{0}, Phone Number: {1})".format( self.name, self.phoneNumber)) class Student(Person): def __init__(self, name, phoneNumber, subject, studentID): # override # pyhon은 부모를 참조하는 base, super 키워드가 없다 # 자동으로 불러주지 않아서 직접 호출해야함 Person.__init__(self, name, phoneNumber) # 명시적으로 부모 클래스 생성자 호출 self.subject = subject self.studentID = studentID def printInfo(self): # override print("Info(Name:{0}, Phone Number: {1})".format( self.name, self.phoneNumber)) print(f"Info(Subject:{self.subject}, StudentID: {self.studentID})") p = Person("전우치", "010-222-1234") s = Student("이순신", "010-111-1234", "컴공", "991122") p.printInfo() s.printInfo() p.__dict__ # Attribute를 dict 형식으로 출력 s.__dict__ # 상속관계 체크 issubclass(자식 클래스, 부모 클래스) issubclass(Student, Person) class SuperClass: def __init__(self): self.x = 10 def printX(self): print(self.x) class SubClass(SuperClass): def __init__(self): # SuperClass.__init__(self) # 직접 부모를 호출하지 않으면 부모 클래스 데이터를 상속받지 못함 self.y = 20 def printY(self): print(self.y) class SubClassB(): def __init__(self): SuperClass.__init__(self) # 참조로 넘긴 self만 영향이 갈 뿐 상속이 아님 self.y = 20 def printY(self): print(self.y) s = SubClass() s.a = 30 print("SuperClass: ", SuperClass.__dict__) # printX()가 저장됨 print("SubClass : ", SubClass.__dict__) # printY()만 저장됨(printX()가 없음) print("s : ", s.__dict__) # y, a가 저장되어 있음(x가 없음) sb = SubClassB() sb.__dict__ sb.x sb.printX() # 에러 ### # 다중 상속 # 지원은 하지만 클래스간 충돌 가능성때문에 잘 안씀 ### class Tiger: def jump(self): print("호랑이 점프") def cry(self): print("호랑이 어흥~~") class Lion: def bite(self): print("사자 물어뜯기") def cry(self): print("사자 으르릉~~") class Liger(Tiger, Lion): # 순서에 따라 중복시 오버라이드 우선순위가 결정됨 def play(self): print("라이거와 놀기") l = Liger() l.play() l.jump() l.bite() l.cry() # Tiger 클래스의 cry() 호출 print("Liger클래스의 MRO:", Liger.__mro__) ### # 모듈과 패키지 # 모듈 : 하나의 파일에 담긴 함수와 클래스들 # 패키지 : 디렉토리에 여러 개의 모듈이 담김. 모듈에 namespace 제공 # dir() : namespace 확인 # import <모듈명> : 해당 모듈을 현재 namespace에 추가 ### dir() # 현재 모듈 namespace import math dir(math) # math 모듈 namespace math.pow(2,10) math.log(100) math.cos(2) math.pi import glob # 폴더 파일 목록 가져오는 모듈 fileList = glob.glob("c:\work\*.py") for item in fileList: print(item) import sys sys.modules # 실습 simpleset.py 파일을 python38->Lib 폴더에 복사하면 기존 라이브러리처럼 사용 가능 # 내장 함수 디렉토리기 때문에 권장하지 않음 import simpleset simpleset # python38/Lib setA = [1,2,3] setB = [3,4,5] simpleset.union(setA, setB) simpleset.intersect(setA, setB) dir(simpleset) # PYTHONPATH(예약됨) 환경변수에 사용자 모듈 패스를 추가하여 관리하는것이 안전하고 권장됨 import simpleset simpleset # /mymodule # 모듈 이름 다르게 가져오기 import math as mt # 모듈 해제 del math # 일부 모듈만 가져오기 : from <모듈> import <어트리뷰트> # 해당 속성은 모듈 참조없이 어트리뷰트 바로 접근 가능(현재 namespace 추가) # 모듈명 namespace에 추가하지않고 어트리뷰트 전체 가져오기 : from <모듈> import * # 모듈 내 _ 로 시작하는 어트리뷰트를 제외하고 모든 어트리뷰트를 현재 namespace에 추가 # 어트리뷰트를 직접 현재 namespace 에 추가하는건 간단히 사용하기 좋지만 충돌 발생 가능성이 있음 from simpleset import union union([1,2,3], [3,4,5]) # simpleset 참조없이 바로 메서드 사용 dir() # 모듈 동적 추가 import sys sys.path sys.path.append("c:\mymodule") sys.path.remove("c:\mymodule") ### # 바이트 코드 : # python은 기계어 코드가 없지만 빠른 import을 위해 # 바이트 코드라는 모듈에 대한 캐싱코드가 존재 # 모듈 디렉토리의 __pycache__ 하위 디렉토리에 자동으로 생긴다. ### ### # pyinstaller 를 이용해서 파이썬 코드를 실행 파일(exe)로 만들기 # 1. > pip installer pyinstaller # 2. > pyinstaller test.py # 3. 해당 작업 디렉토리에 build 및 dist 폴더가 만들어짐 # 4. dist 폴더에 실행파일이 생성되어있음 ### # 같은 모듈에 대해 두 개이상의 별칭 사용하는 예제 import testmodule as t1 import testmodule as t2 dir() t1.defualttvalue = 100 t2.printDefaultValue() ### 패키지 # from-import 절로 모듈단위로 namespace 생성하여 사용하는 예제 # https://wikidocs.net/1418 패키지 개요 ### from DemoPackage import demo1 dir() demo1.myfunc1() demo1.myfunc2() from DemoPackage import demo2 demo2.func1() demo2.func2() # import 로 패키지의 모듈을 불러오면 접근이 길어진다 # import 접근은 모듈단위까지만 가능 import DemoPackage.demo1 DemoPackage.demo1.myfunc1() ### 파일 입출력 # open(file, mode) # mode -> r(읽기, 기본값), w(쓰기), a(쓰기 + 이어쓰기), +(읽기+쓰기), b(바이너리), t(텍스트, 기본값) ### f = open("c:\\work\\test.txt", "wt") f.write("aaaㅎㅇ\nbbb") f.close() f = open("c:\\work\\test.txt") f.read() f.close() f.closed ## 파일 입력 함수 # EOF 까지 포인터 이동하며 반환 # read() : str 리턴 # readlines() : list 리턴 ["~", "~"] 1줄 단위로 인덱스추가 # readline() : 1줄 단위로 str리턴 ## f = open("c:\\work\\test.txt") f.read() f.tell() f.seek(0) # 파일 포인터를 0(처음)으로 이동 list = [] list += f.readline() f.seek(0) list2 = f.readlines() ### 예외처리 # except [발생 오류[as 오류 메시지 변수]] try: 4/0 except ZeroDivisionError as e: print(e) pass # 통과 else: # 예외가 발생하지 않을시 실행 print("else") finally: # 예외 여부 상관없이 try절 마친 후 항상 실행 print("finally")6.
# 파이썬 인터프리터 변경하기 (conda) # ctrl + shift + p 에서 select interpreter 한다음 conda 버전으로 변경 # 좌측 하단에 ('base':conda) 로 인터프리터가 변경된것을 확인 # 프롬프트 창에서는 conda activate base 명령으로 conda 인터프리터로 변경가능 # terminal 창을 powershell이 아닌 cmd 창으로 변경 def hello(count): for item in range(count): print("hello world") if __name__ == "__main__": hello(3)7.
import os import sqlite3 # 더 깊이 공부하고 싶으면 sqliteAlchemy ### # 시스템에서 인식하는 루트디렉토리 경로는 현재 vscode의 워킹디렉토리이다. ### def example1(): if not os.path.exists("python_study/db/myDB.db"): # 파일 존재 여부 확인 conn = sqlite3.connect('python_study/db/mydb.db') with conn: cursor = conn.cursor() cursor.execute('Drop Table if exists cars;') cursor.execute('CREATE TABLE cars(id int, name text, price int)') cursor.execute("Insert Into cars values(1, 'Audi', 52542)") cursor.execute("Insert Into cars values(2, 'Mercedes', 57127)") cursor.execute("Insert Into cars values(3, 'skoda', 90000)") cursor.execute("Insert Into cars values(4, 'Volvo', 290000)") cursor.execute("Insert Into cars values(5, 'Bentlery', 3500000)") #conn.close() else: conn = sqlite3.connect('python_study/db/mydb.db') with conn: cursor = conn.cursor() cursor.execute('select * from cars') rows = cursor.fetchmany(3) print(rows) print(cursor.lastrowid) example1() ### # db에 execute 하다보면 연관된 정보를 동시에 생성할필요가 생긴다. # 이 경우 아이디 값을 알아야하는데 이 트랜잭션을 단순히 분리해서 # 아이디 값을 찾아내는 코드를 작성하면 안된다. # lastrowid => excute 한 테이블의 마지막 행 id 값을 가져와준다. # 자기 자신 curosr가 건든 값만 가져오므로 정보를 동시에 만드는 시도가 있어도 # 영향을 받지 않는다. ### def example2(): if os.path.exists("python_study/db/myDB.db"): # 파일 존재 여부 확인 conn = sqlite3.connect('python_study/db/mydb.db') with conn: cur = conn.cursor() cur.execute("CREATE TABLE friends(id INTEGER PRIMARY KEY, name TEXT);") cur.execute("INSERT INTO friends(name) VALUES ('Tom');") cur.execute("INSERT INTO friends(name) VALUES ('Rebecca');") cur.execute("INSERT INTO friends(name) VALUES ('Jim');") cur.execute("INSERT INTO friends(name) VALUES ('Robert');") last_row_id = cur.lastrowid print(f"The last Id of the inserted row is {last_row_id}") example2() ## def example3(): if os.path.exists("python_study/db/myDB.db"): # 파일 존재 여부 확인 conn = sqlite3.connect('python_study/db/mydb.db') with conn: cur = conn.cursor() cur.execute("SELECT * FROM cars") rows = cur.fetchall() for row in rows: print(f"{row[0]:>2} {row[1]:>12} {row[2]:8}") example3() ### # conn.row_factory # 각 레코드는 사전과 비슷하다. # 커서에 대해서 row_factory 값을 지정하여 개별 행을 원하는 # python 타입으로 변환할 수 있다. # sqlite3.Row를 사용하면 key:value 객체 반환 dict에 전달하여 변환가능 ### def example4(): if os.path.exists("python_study/db/myDB.db"): # 파일 존재 여부 확인 conn = sqlite3.connect('python_study/db/mydb.db') with conn: conn.row_factory = sqlite3.Row # cur = conn.cursor() cur.execute("SELECT * FROM cars") rows = cur.fetchall() for row in rows: print(f"{row['id']} {row['name']} {row['price']}") example4() def example5(): uId = 1 uPrice = 62600 con = sqlite3.connect('python_study/db/myDB.db') with con: cur = con.cursor() cur.execute("UPDATE cars SET price=? WHERE id=?", (uPrice, uId)) print(f"Number of rows updated: {cur.rowcount}") example5() def example6(): uId = 1 uPrice = 62600 con = sqlite3.connect('python_study/db/myDB.db') with con: cur = con.cursor() cur.execute("UPDATE cars SET price=? WHERE id=?", (uPrice, uId)) con.commit() print(f"Number of rows updated: {cur.rowcount}") cur.execute('select * from cars where id=:Id', {'Id' : uId}) row = cur.fetchone() print(row) example6() import sqlite3 import os import sys ## 이미지 파일을 db에 저장하기 def example7(): def read_img(uri): fin = None try: fin = open(uri, 'rb') img = fin.read() return img except IOError as e: print(e) sys.exit(1) finally: if fin: fin.close() try: conn = sqlite3.connect('python_study/db/myDB.db') cur = conn.cursor() data = read_img('python_study/imgs/tarte.jpg') binary = sqlite3.Binary(data) print(binary) cur.execute('insert into imgs(data) VALUES(?)', (binary,)) conn.commit() except sqlite3.Error as e: if conn: conn.rollback() print(e) sys.exit(1) example7() ### # sqlite 에 저장한 이미지바이너리를 가져와 이미지 파일로 출력하기 ### def example8(): def writeImage(data): fout = None try: fout = open('python_study/imgs/write_cookie.jpg', 'wb') fout.write(data) except IOError as ioe: print(ioe) sys.exit(1) finally: if fout: fout.close() conn = None try: conn = sqlite3.connect('python_study/db/myDB.db') cur = conn.cursor() cur.execute('select data from imgs limit 1') data = cur.fetchone()[0] print(os.getcwd()) writeImage(data) except sqlite3.Error as e: print(e) sys.exit(1) finally: if conn: conn.close() example8()'Python' 카테고리의 다른 글
Python 시퀀스 데이터 다루기(jupyter notebook 실습) (0) 2021.11.08 Python 크롤링 공부 (0) 2021.11.08 [Python] import 문에서 에러 발생시 체크사항(ModuleNotFoundError ) (0) 2021.06.05