Python 요약 정리

Certificate

좋은 어플이 있다. “Learn Python” 시간날 때마다 짬잠히 보다보니 일주일만에
완독. 단계별 설명, 예제, 실습, 연습문제, 단계별 평가문제까지 구성이 굉장히 잘
되어 있다. 다른 언어를 사용한 경험이 있다면 아주 쉽게 학습이 가능하다.
다만 문법중에 외워서 사용해야 할 것들이 있으니 Java 와 syntax 나 개념이
상이한 것 위주로 요약 노트처럼 정리해 보고자 한다.

가) Basic Concept

– 11 / 0 : 0으로 나누면 ZeroDivisionError 발생
– 3/4 = 0.75 : 정수로 나눠도 Float 타입이 된다
– 3 * 2.0 = 6.0 : Float 이랑 곱하면 당연히 Float
– 2**5 : ** 는 제곱 연산
– 20 // 6 = 3 : 몫을 연산한다
– String 은 “abcd”
– 특수문자는 \ 후 입력
– “”” 내용 “”” 으로 표현시 줄바꿈 자동 인식
– print(내용) : 콘솔 출력
– input() : 사용자 입력
-‘x’ * 3 = xxx : num * String 은 String 반복
– int(“1”) , float(“1”) : 타입 변환

나) Control Structures

(1) if
아래의 예제로 if , elif, else 의 문법은 설명이 되었고 특이한 것이 괄호를 사용하지
않고 Space 혹은 Tab 으로 줄을 맞춰서 Depth 을 인식한다는 점이 특이하다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if 10 > 5:
print("XXX")
print("XXX")
if 10 > 5 :
print("YYY")
elif :
print("SSS")
else :
print("ZZZ")
if 10 > 5: print("XXX") print("XXX") if 10 > 5 : print("YYY") elif : print("SSS") else : print("ZZZ")
if 10 > 5: 
    print("XXX")
    print("XXX")
    if 10 > 5 : 
      print("YYY")
elif : 
   print("SSS")
else : 
   print("ZZZ")

(2) boolean
not, and, or 연산자를 사용하여 Boolean 연산을 한다

not 1==1 and 1==2 or 1==1

(3) 기타 연산자2016-08-27-22-15-39

(4) while
예제 보면 java 랑 크게 다른 것은 없다. indent 로 Depth 를 구분한다는 점만 기억

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
while True :
i = i+1
if i==2:
continue
if i==3:
break
while True : i = i+1 if i==2: continue if i==3: break
while True :
  i = i+1 
  if i==2:
    continue
  if i==3:
    break

(5) LIST

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ttt = ["sting", 0 , [1,2,3] , 1.1]
print ttt[2][2]
# 2 출력
str = "abcd"
print(str[1])
# b 출력
nums = [1,2,3]
print(nums + [4,5,6])
print(nums * 2)
# [1,2,3,4,5,6]
# [1,2,3,1,2,3]
str = ["aaa", "bbb" ,"ccc"]
print("aaa" in str)
print("aaa" not in str)
#true
#false
ttt = ["sting", 0 , [1,2,3] , 1.1] print ttt[2][2] # 2 출력 str = "abcd" print(str[1]) # b 출력 nums = [1,2,3] print(nums + [4,5,6]) print(nums * 2) # [1,2,3,4,5,6] # [1,2,3,1,2,3] str = ["aaa", "bbb" ,"ccc"] print("aaa" in str) print("aaa" not in str) #true #false
ttt = ["sting", 0 , [1,2,3] , 1.1]
print ttt[2][2] 
# 2 출력 

str = "abcd"
print(str[1])
# b 출력 

nums = [1,2,3] 
print(nums + [4,5,6])
print(nums * 2) 
# [1,2,3,4,5,6]
# [1,2,3,1,2,3]

str = ["aaa", "bbb" ,"ccc"] 
print("aaa" in str) 
print("aaa" not in str)
#true
#false
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
nums = [1,2,3]
nums.append(4)
#[1,2,3,4]
len(nums)
#4
nums.insert(0,0)
#[0,1,2,3,4]
str = ['a','b','c']
str.index('a')
#0
nums = [1,2,3] nums.append(4) #[1,2,3,4] len(nums) #4 nums.insert(0,0) #[0,1,2,3,4] str = ['a','b','c'] str.index('a') #0
nums = [1,2,3]
nums.append(4) 

#[1,2,3,4]

len(nums)

#4

nums.insert(0,0)

#[0,1,2,3,4]

str = ['a','b','c']
str.index('a')

#0

 

(6) Range

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
range(5)
range(0,5)
range(0,5,2)
#[0,1,2,3,4]
#[0,1,2,3,4]
#[0,2,4]
range(5) range(0,5) range(0,5,2) #[0,1,2,3,4] #[0,1,2,3,4] #[0,2,4]
range(5) 
range(0,5)
range(0,5,2)

#[0,1,2,3,4]
#[0,1,2,3,4]
#[0,2,4]

 

(7) for

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
words = ["aaa","bbb","ccc"]
for word in words:
print(word)
#aaa
#bbb
#ccc
words = ["aaa","bbb","ccc"] for word in words: print(word) #aaa #bbb #ccc
words = ["aaa","bbb","ccc"]
for word in words:
  print(word)

#aaa
#bbb
#ccc

다. Function & Module

(1) function
function 도 마찬가지로 아래 예제 하나면 끝

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def add(x,y):
return x + y
def test(func, x, y)
return func(func(func(x,y), func(x,y))
a = 5
b = 10
print(test(add, a, b))
#30
def add(x,y): return x + y def test(func, x, y) return func(func(func(x,y), func(x,y)) a = 5 b = 10 print(test(add, a, b)) #30
def add(x,y):
  return x + y 

def test(func, x, y)
  return func(func(func(x,y), func(x,y))

a = 5
b = 10 

print(test(add, a, b))

#30

(2) 주석

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# abcd abcd
""" abcd abcd
abcd abcd
"""
# abcd abcd """ abcd abcd abcd abcd """
# abcd abcd  

""" abcd abcd 
    abcd abcd 
"""

(3) Module

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import random as ran
ran.randint(1,6) # 1~6사이 랜덤
from math import pi # from 은 패키지 경로 import 는 Class
import random as ran ran.randint(1,6) # 1~6사이 랜덤 from math import pi # from 은 패키지 경로 import 는 Class
import random as ran
ran.randint(1,6) # 1~6사이 랜덤 

from math import pi # from 은 패키지 경로 import 는 Class

 

라. Exception & File

(1) Exception 종류

2016-08-27-22-51-02

 

(2) Exception Catch

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try :
print("xxx")
exception 캐치할 종류
print("--------")
finally:
print("xxxxxxx")
try : print("xxx") exception 캐치할 종류 print("--------") finally: print("xxxxxxx")
try : 
  print("xxx")
exception 캐치할 종류 
  print("--------")
finally:
  print("xxxxxxx")

(3) Raise Exception

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
raise NameError("invaild Name Error")
#NameError : invaild Name Error
raise NameError("invaild Name Error") #NameError : invaild Name Error
raise NameError("invaild Name Error")

#NameError : invaild Name Error

(4) Assertions

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def aaa(x,y):
return x+y
asert aaa(1,1) == 3
#AssertionError
def aaa(x,y): return x+y asert aaa(1,1) == 3 #AssertionError
def aaa(x,y):
  return x+y 
asert aaa(1,1) == 3 

#AssertionError

(5) Opening Files

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
file = open("filename.txt" , "w") # 쓰기 모드
file = open("filename.txt" , "r") # 일기 모드
file = open("filename.txt" , "wb") # 바이트 쓰기 모드
file.write("xxxxx")
file.read()
finally:
file.close()
try: file = open("filename.txt" , "w") # 쓰기 모드 file = open("filename.txt" , "r") # 일기 모드 file = open("filename.txt" , "wb") # 바이트 쓰기 모드 file.write("xxxxx") file.read() finally: file.close()
try:
  file = open("filename.txt" , "w")   # 쓰기 모드 
  file = open("filename.txt" , "r")   # 일기 모드 
  file = open("filename.txt" , "wb")  # 바이트 쓰기 모드 

  file.write("xxxxx")
  file.read()
finally:
  file.close()

마. 다른 타입

(가) Null = NONE

(나) Dictionaries

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dic = {
"red" :[255,0,0],
"blue" :[255,0,0],
"green" :[255,0,0],
}
print(dic["red"])
#[255,0,0]
print("red" in dic)
#true
print(dic.get("red"))
#[255,0,0]
print(dic.get("xxx"))
#None
dic = { "red" :[255,0,0], "blue" :[255,0,0], "green" :[255,0,0], } print(dic["red"]) #[255,0,0] print("red" in dic) #true print(dic.get("red")) #[255,0,0] print(dic.get("xxx")) #None
dic = { 
  "red" :[255,0,0],
  "blue" :[255,0,0],
  "green" :[255,0,0],
}

print(dic["red"])
#[255,0,0]

print("red" in dic)
#true 

print(dic.get("red"))
#[255,0,0]

print(dic.get("xxx"))
#None

(다) Tuples

Tuple 은 변형이 불가능한 데이터 타입  그 외의 속성은 리스트와 동일

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
tup = ("aaa","bbb","ccc")
tup = ("aaa","bbb","ccc")
tup = ("aaa","bbb","ccc")

(라) List

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
squa = [0,1,2,3,4,5,6]
print(squa[0:2])
print(squa[:2]) # 표시 안하면 무한대 R문법 이랑 비슷
print(squa[2:])
print(squa[2::2] # 2부터 2개씩 끝날때 까지
print(squa[2:-1] # 2부터 맨뒤에서 하나 빼고
squa = [0,1,2,3,4,5,6] print(squa[0:2]) print(squa[:2]) # 표시 안하면 무한대 R문법 이랑 비슷 print(squa[2:]) print(squa[2::2] # 2부터 2개씩 끝날때 까지 print(squa[2:-1] # 2부터 맨뒤에서 하나 빼고
squa = [0,1,2,3,4,5,6]
print(squa[0:2])
print(squa[:2])  # 표시 안하면 무한대 R문법 이랑 비슷
print(squa[2:])
print(squa[2::2] # 2부터 2개씩 끝날때 까지 
print(squa[2:-1] # 2부터 맨뒤에서 하나 빼고

(마) List 조건문

이런 부분들은 R 과 유사한 점이 많다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
evens = [i**2 for i in range(10) if i**2 %2==0] # 0~9 까지짝수의 제곱
#[0,4,16,36,64]
evens = [i**2 for i in range(10) if i**2 %2==0] # 0~9 까지짝수의 제곱 #[0,4,16,36,64]
evens = [i**2 for i in range(10) if i**2 %2==0]  # 0~9 까지짝수의 제곱 
#[0,4,16,36,64]

(바) String Formatting

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
nums = [4,5,6]
msg = "Number: {0}{1}{2}".format(nums[0],nums[1],nums[2])
print(msg)
#Number : 4 5 6
nums = [4,5,6] msg = "Number: {0}{1}{2}".format(nums[0],nums[1],nums[2]) print(msg) #Number : 4 5 6
nums = [4,5,6]
msg = "Number: {0}{1}{2}".format(nums[0],nums[1],nums[2])
print(msg)

#Number : 4 5 6

(사) 유용한 기능들

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print(",".join(["spam","eggs","ham"]))
#"spam,eggs,ham"
print("Hello Me".replace("ME","world"))
#Hello Wrold
print("this is a senstence.".startswith("this"))
#true
print("this is a sensrence.".ensswith("sentence."))
#true
print("this is a senstence".upper())
#THIS IS A SENSTENCE
print("AN ALL CAPS SENTENCE".lower())
#an all caps sentence
print("spam, eggs, ham".split(","))
#["spam","eggs","ham"]
print(",".join(["spam","eggs","ham"])) #"spam,eggs,ham" print("Hello Me".replace("ME","world")) #Hello Wrold print("this is a senstence.".startswith("this")) #true print("this is a sensrence.".ensswith("sentence.")) #true print("this is a senstence".upper()) #THIS IS A SENSTENCE print("AN ALL CAPS SENTENCE".lower()) #an all caps sentence print("spam, eggs, ham".split(",")) #["spam","eggs","ham"]
print(",".join(["spam","eggs","ham"]))
#"spam,eggs,ham"

print("Hello Me".replace("ME","world"))
#Hello Wrold 

print("this is a senstence.".startswith("this"))
#true 

print("this is a sensrence.".ensswith("sentence.")) 
#true 

print("this is a senstence".upper())
#THIS IS A SENSTENCE

print("AN ALL CAPS SENTENCE".lower())
#an all caps sentence 

print("spam, eggs, ham".split(","))
#["spam","eggs","ham"]
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print(min(1,2,3,4,5))
#1
print(max([1,2,3,4,5])
#5
print(abs(-99))
#99
print(abs(42))
#42
print(sum([1,2,3,4,5]))
#15
print(min(1,2,3,4,5)) #1 print(max([1,2,3,4,5]) #5 print(abs(-99)) #99 print(abs(42)) #42 print(sum([1,2,3,4,5])) #15
print(min(1,2,3,4,5))
#1
print(max([1,2,3,4,5])
#5
print(abs(-99))
#99
print(abs(42))
#42
print(sum([1,2,3,4,5]))
#15
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
nums = [55,44,22,33,11]
if all([i>5 for i in nums]):
print("true 1")
# true 1
if any([i%2 ==0 for i in nums]):
print("true 2")
# true 2
for v in enumerate(nums):
print(v)
# (0,55)
# (1,44)
# (2,22)
nums = [55,44,22,33,11] if all([i>5 for i in nums]): print("true 1") # true 1 if any([i%2 ==0 for i in nums]): print("true 2") # true 2 for v in enumerate(nums): print(v) # (0,55) # (1,44) # (2,22)
nums = [55,44,22,33,11]
if all([i>5 for i in nums]):
  print("true 1")
# true 1

if any([i%2 ==0 for i in nums]):
  print("true 2")
# true 2

for v in enumerate(nums):
  print(v)
# (0,55)
# (1,44)
# (2,22)

바 . Functional Programming

(1) Lamda

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print((lambda x:x**2 +5)(-4))
# -11 출력
double = lambda x:x*2
print(double(7))
# 14 출력
print((lambda x:x**2 +5)(-4)) # -11 출력 double = lambda x:x*2 print(double(7)) # 14 출력
print((lambda x:x**2 +5)(-4))
# -11 출력 

double = lambda x:x*2 
print(double(7))
# 14 출력

(2) map

뭔가 R 에 있는 apply 류 함수 같은 느낌의 함수들

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def add_five(x):
return x+5
nums = [11,22,33]
result = list(map(addfive, nms)) # 함수 적용
print(result)
# [16,27,38]
res = list(filter(lambda x:x%2==0, nums)) # 조건 검색
print(res)
# [16, 38]
def add_five(x): return x+5 nums = [11,22,33] result = list(map(addfive, nms)) # 함수 적용 print(result) # [16,27,38] res = list(filter(lambda x:x%2==0, nums)) # 조건 검색 print(res) # [16, 38]
def add_five(x):
  return x+5 

nums = [11,22,33]
result = list(map(addfive, nms))           # 함수 적용
print(result)
# [16,27,38]

res = list(filter(lambda x:x%2==0, nums))  # 조건 검색 
print(res)
# [16, 38]

 

(3) Generators

이건 좀 생소하다. 마치 일반 변수를 즉석해서 array로 만든느 그럼 느낌

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def countdown():
i=5
while i>0:
yield i
i -= 1
for i in countdown():
print(i)
#5
#4
#3
#2
#1
def numbers(x):
for i in range(x):
if i%2 ==0:
yield i
print(list(numbers(11)))
#[1,2,4,6,8,10]
def countdown(): i=5 while i>0: yield i i -= 1 for i in countdown(): print(i) #5 #4 #3 #2 #1 def numbers(x): for i in range(x): if i%2 ==0: yield i print(list(numbers(11))) #[1,2,4,6,8,10]
def countdown():
i=5
  while i>0:
    yield i
    i -= 1

for i in countdown():
  print(i)

#5
#4
#3
#2
#1

def numbers(x):
  for i in range(x):
    if i%2 ==0:
      yield i

print(list(numbers(11)))

#[1,2,4,6,8,10]

 

(4) decoration

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def decor2(func): def wrap():
print("============")
func()
print("============")
return wrap
@decor2
def print_text():
print("Hello World!")
print_text();
#==============
#Hello World!
#==============
def decor2(func): def wrap(): print("============") func() print("============") return wrap @decor2 def print_text(): print("Hello World!") print_text(); #============== #Hello World! #==============
def decor2(func):  def wrap():
    print("============")
    func()
    print("============")
  return wrap

@decor2 
def print_text():
  print("Hello World!")

print_text();

#==============
#Hello World!
#==============

 

(5) recursion

여기서 if x==1 구문이 없으면 무한 반복이 되어 애러가 난다, recursion 은
무한 반복이 되지 않도록 End 지점을 지정하는 것이 중요하다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def factorial(x):
if x== 1:
return 1
else :
return x * factoral(x-1)
print(factoral(5))
#120
def factorial(x): if x== 1: return 1 else : return x * factoral(x-1) print(factoral(5)) #120
def factorial(x):
  if x== 1:
    return 1 
  else :
    return x * factoral(x-1)

print(factoral(5))

#120

 

(6) Data Structures

– Dictionaries : Key:Value  , 변경 가능
. {key :vlaue , key:value }
– Lists : 순차적 접근, 중복허용, 변경 가능
. [1,2,3,4,]
– Tuple : 중복 허용, 순차적 접근, 변경 불가
. (1,2,3,4,)
– Sets : 중복 불가, 변경 가능
. {1,2,3,4,}
. sets = set([1,2,3,4,])

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
nums = {1,1,2,2,3,3,}
nums.add(-1)
print(nums)
nums.remove(1)
print(nums)
# {-1,1,2,3,}
# {-1,2,3,}
fi = {1,2,}
se = {2,3,}
print(fi | se)
print(fi & se)
print(fi -se)
print(fi ^ se)
# {1,2,3,}
# {2}
# {1}
# {1,3,}
nums = {1,1,2,2,3,3,} nums.add(-1) print(nums) nums.remove(1) print(nums) # {-1,1,2,3,} # {-1,2,3,} fi = {1,2,} se = {2,3,} print(fi | se) print(fi & se) print(fi -se) print(fi ^ se) # {1,2,3,} # {2} # {1} # {1,3,}
nums = {1,1,2,2,3,3,}
nums.add(-1)
print(nums)
nums.remove(1)
print(nums)

# {-1,1,2,3,}
# {-1,2,3,}

fi = {1,2,}
se = {2,3,}
print(fi | se)
print(fi & se)
print(fi -se)
print(fi ^ se)

# {1,2,3,}
# {2}
# {1}
# {1,3,}

 

(7) Itertools

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from itertools import count, cycle, repeat, accumulate, takewhile, product, permutations
for i in count(3) # 3부터 무한대로 증가
for i in cycle(리스트) # 리스트 무한반복
for i in repeat(오브젝트) # 오브젝트 반복
list(accumulate(range(5)) # 1,3,6 이런식으로 누계 연산
list(takewhile(lambda x:x <=6, nums)) # 조건에 맞는 대상 리턴
letters1 = ("A","B")
letters2 = ("C","D")
list(product(letters1, letters2))
# [('A','C') , ('A','D'), ('B','C'),('B','D')]
list(permutation(letters1))
# [('A','B') , ('B','A')]
from itertools import count, cycle, repeat, accumulate, takewhile, product, permutations for i in count(3) # 3부터 무한대로 증가 for i in cycle(리스트) # 리스트 무한반복 for i in repeat(오브젝트) # 오브젝트 반복 list(accumulate(range(5)) # 1,3,6 이런식으로 누계 연산 list(takewhile(lambda x:x <=6, nums)) # 조건에 맞는 대상 리턴 letters1 = ("A","B") letters2 = ("C","D") list(product(letters1, letters2)) # [('A','C') , ('A','D'), ('B','C'),('B','D')] list(permutation(letters1)) # [('A','B') , ('B','A')]
from itertools import count, cycle, repeat, accumulate, takewhile, product, permutations 

for i in count(3) # 3부터 무한대로 증가
for i in cycle(리스트) # 리스트 무한반복 
for i in repeat(오브젝트) # 오브젝트 반복 
list(accumulate(range(5)) # 1,3,6 이런식으로 누계 연산 
list(takewhile(lambda x:x <=6, nums)) # 조건에 맞는 대상 리턴 

letters1 = ("A","B")
letters2 = ("C","D")

list(product(letters1, letters2))
# [('A','C') , ('A','D'), ('B','C'),('B','D')]

list(permutation(letters1))
# [('A','B') , ('B','A')]

 

사. Object Oriented Programming

(1) Class

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("!!!")
fido = Dog("AAA", "BBB")
print(fido.name)
fido.bark()
#AAA
#!!!
class Dog: def __init__(self, name, color): self.name = name self.color = color def bark(self): print("!!!") fido = Dog("AAA", "BBB") print(fido.name) fido.bark() #AAA #!!!
class Dog:
  def __init__(self, name, color):
    self.name = name 
    self.color = color 
  
  def bark(self):
    print("!!!")

fido = Dog("AAA", "BBB")
print(fido.name)
fido.bark()

#AAA
#!!!

 

(2) Inheritance

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Animal
def __init__(self, name)
self.name = name
def action (self)
print(name)
class Cat(Animal) # 상속
def action(self) # override
print(self.name + " - override")
cats = Cat("KKK")
cats.action()
# KKK - override
class Animal def __init__(self, name) self.name = name def action (self) print(name) class Cat(Animal) # 상속 def action(self) # override print(self.name + " - override") cats = Cat("KKK") cats.action() # KKK - override
class Animal 
  def __init__(self, name)
    self.name = name 
  def action (self)
    print(name)

class Cat(Animal)                         # 상속 
  def action(self)                        # override 
    print(self.name + " - override")

cats = Cat("KKK")
cats.action() 
# KKK - override

 

(3) Magic Methods

기본 연산자를 Overrideing 할 수 있는 Method 명들이 있다. 이런 메서드는
통상적으로 __XXXX__ 이런 모양을 갖는데. 예를 들면 이런식이다. __add__()
이런 메서드는 funcA + funcB 연산을 할때 동작한다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Vector2D:
def __init__(self, x,y)
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.X , self.y+ other.y)
first = Vecto2D(5,7)
second = Vector2D(3,9)
result = first + second
print(result.x)
print(result.y)
#8
#16
class Vector2D: def __init__(self, x,y) self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.X , self.y+ other.y) first = Vecto2D(5,7) second = Vector2D(3,9) result = first + second print(result.x) print(result.y) #8 #16
class Vector2D:
  def __init__(self, x,y)
    self.x = x 
    self.y = y
  def __add__(self, other):
    return Vector2D(self.x + other.X , self.y+ other.y)

first = Vecto2D(5,7)
second = Vector2D(3,9)
result = first + second 
print(result.x)
print(result.y)

#8
#16

 

2016-08-28-11-48-21

2016-08-28-11-48-40

2016-08-28-11-49-00

(4) Data Hiding

JAVA 에서 Private 변수 같은 것에 대한 설명인데
_XXXX 언더바 한번은 접근은 가능하지만 그냥 이건 내부에서 쓰는 용도다라고 선언
하는 정도로 사용하는 것이다
__XXXX 언더바 두번은 그냥은 접근이 안되도록 실질적으로 차단이 되지만, 구지
바로 접근하고자 한다면 아래와 같이 접근은 가능하다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Spam:
__egg = 7
def print_egg(self):
print(self.__egg)
s = Spam()
s.print_egg() #접근 가능
print(s._Spam__egg) #접근 가능
print(s.__egg) #접근 불가
class Spam: __egg = 7 def print_egg(self): print(self.__egg) s = Spam() s.print_egg() #접근 가능 print(s._Spam__egg) #접근 가능 print(s.__egg) #접근 불가
class Spam:
  __egg = 7 
  def print_egg(self):
    print(self.__egg)

s = Spam()
s.print_egg()          #접근 가능 
print(s._Spam__egg)    #접근 가능 
print(s.__egg)         #접근 불가

 

(5) Class & Static Methods

지금까지 설명한 Class 의 Method 들은 self 파라메터를 받는 종류의 메서드들
이었다면, Class Method 는 Class 자체를 받아서 사용가능한 형태의 메서드이며,
Static Method 는 slef도 cls 도 받지 않고 독립적으로 사용가능한 메서드이다
※ Class Method 는 Java 의 Constructor 처럼 사용하면 될 것으로 보인다.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Rectangle:
name = None
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return str(self.width * self.height) + name
@classmethod
def new_square(cls, side_length, name):
cls.name = name
return cls(side_length, side_length)
@staticmethod
def testtest(width, height):
if(widht * height > 10)
print("too big")
square = Rectangle.new_square(5, "xxx")
print(square.calculate_area())
# 25XXX
Rectangle.testtest(10,10)
#too big
class Rectangle: name = None def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return str(self.width * self.height) + name @classmethod def new_square(cls, side_length, name): cls.name = name return cls(side_length, side_length) @staticmethod def testtest(width, height): if(widht * height > 10) print("too big") square = Rectangle.new_square(5, "xxx") print(square.calculate_area()) # 25XXX Rectangle.testtest(10,10) #too big
class Rectangle:
  name = None 
  def __init__(self, width, height):
    self.width = width 
    self.height  = height 

  def calculate_area(self):
    return str(self.width * self.height) + name 

  @classmethod 
  def new_square(cls, side_length, name):
    cls.name = name 
    return cls(side_length, side_length)

  @staticmethod 
  def testtest(width, height):
    if(widht * height > 10) 
      print("too big")

square = Rectangle.new_square(5, "xxx") 
print(square.calculate_area()) 
# 25XXX

Rectangle.testtest(10,10)
#too big

 

(6) Properties

JAVA 의 Getter , Setter 를 지정해 놓고 완전히 변수처럼 사용하는 문법
아래 예제에서는 사용자 input 를 받아서 처리하는 응용로직이 들어 있지만, 단순하게
사용한다면, getter, setter 처러 사용하면 어떨까 싶다

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
self._pineapple_allowed = False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
@pineapple_allowed.setter
def pineapple_allowed(self, value):
if value:
password = input("Enter the password: ")
if password == "Sw0rdf1sh!":
self._pineapple_allowed = value
else:
raise ValueError("Alert! Intruder!")
pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)
class Pizza: def __init__(self, toppings): self.toppings = toppings self._pineapple_allowed = False @property def pineapple_allowed(self): return self._pineapple_allowed @pineapple_allowed.setter def pineapple_allowed(self, value): if value: password = input("Enter the password: ") if password == "Sw0rdf1sh!": self._pineapple_allowed = value else: raise ValueError("Alert! Intruder!") pizza = Pizza(["cheese", "tomato"]) print(pizza.pineapple_allowed) pizza.pineapple_allowed = True print(pizza.pineapple_allowed)
class Pizza:

  def __init__(self, toppings):
    self.toppings = toppings
    self._pineapple_allowed = False

  @property
  def pineapple_allowed(self):
    return self._pineapple_allowed

  @pineapple_allowed.setter
  def pineapple_allowed(self, value):
    if value:
      password = input("Enter the password: ")
      if password == "Sw0rdf1sh!":
        self._pineapple_allowed = value
      else:
        raise ValueError("Alert! Intruder!")

pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)

 


 

아. Regural Expression

(1) character Classes

Java 나 Javascript 에 보면 String 패턴 비교하는 문법들에 대한 설명

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import re #regural Expression Class
pattern1 = r"[aeiou]" #찾을 패턴 정의시에는 앞에 r 을 넣어 줌
pattern2 = r"abcd" #abcd 패턴을 찾음
pattern3 = r"[abcd]" #a, b , c, d 가 들어 있는 패턴을 찾음
pattern4 = r"[A-Z][0-9]" #A ~ Z , 0 ~ 9 가 들어 있는 패턴 찾음
pattern5 = r"^[A-Z]" #A ~ Z 가 아닌 모든 패턴 찾음
pattern6 = r"a(bcd)*" #a , abcd , abcdbcd (bcd)는 0번~무한대
pattern7 = r"a(bcd)+" # (bcd) 한번 이상
pattern8 = r"a(bcd)?" # (bcd) 0번 or 1번
pattern9 = r"a{1,3}$" # a가 1에서 3번 반복
pattern10 = r"gr.y" # . 자리에는 아무거나 OK
pattern11 = r"^gr.y$" # g로만 시작하면되고 y로만 끝나면 됨
re.search(pattern, "grey")
import re #regural Expression Class pattern1 = r"[aeiou]" #찾을 패턴 정의시에는 앞에 r 을 넣어 줌 pattern2 = r"abcd" #abcd 패턴을 찾음 pattern3 = r"[abcd]" #a, b , c, d 가 들어 있는 패턴을 찾음 pattern4 = r"[A-Z][0-9]" #A ~ Z , 0 ~ 9 가 들어 있는 패턴 찾음 pattern5 = r"^[A-Z]" #A ~ Z 가 아닌 모든 패턴 찾음 pattern6 = r"a(bcd)*" #a , abcd , abcdbcd (bcd)는 0번~무한대 pattern7 = r"a(bcd)+" # (bcd) 한번 이상 pattern8 = r"a(bcd)?" # (bcd) 0번 or 1번 pattern9 = r"a{1,3}$" # a가 1에서 3번 반복 pattern10 = r"gr.y" # . 자리에는 아무거나 OK pattern11 = r"^gr.y$" # g로만 시작하면되고 y로만 끝나면 됨 re.search(pattern, "grey")
import re                        #regural Expression Class 

pattern1 = r"[aeiou]"             #찾을 패턴 정의시에는 앞에 r 을 넣어 줌 
pattern2 = r"abcd"                #abcd 패턴을 찾음 
pattern3 = r"[abcd]"              #a, b , c, d 가 들어 있는 패턴을 찾음 
pattern4 = r"[A-Z][0-9]"          #A ~ Z , 0 ~ 9 가 들어 있는 패턴 찾음 
pattern5 = r"^[A-Z]"              #A ~ Z 가 아닌 모든 패턴 찾음 
pattern6 = r"a(bcd)*"             #a , abcd , abcdbcd (bcd)는 0번~무한대 
pattern7 = r"a(bcd)+"             # (bcd) 한번 이상 
pattern8 = r"a(bcd)?"             # (bcd) 0번 or 1번 
pattern9 = r"a{1,3}$"             # a가 1에서 3번 반복
pattern10 = r"gr.y"               # . 자리에는 아무거나 OK 
pattern11 = r"^gr.y$"             # g로만 시작하면되고 y로만 끝나면 됨 
 
re.search(pattern, "grey")

 

(2) Groups

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
grp1 = r"a(bc)(d(e)f)"
grp2 = r"(?P<fi>abcd)(?:def)(ghi) #?P<fi> = abcd에fi검색tag부착
#def 는 group count 증가 X
grp3 = r"gr(a|e)y" #gray 혹은 grey
re.match(grp, "abcdefghijk")
print(match.group(0)) #abcdefghijk
print(match.group(1)) #bc
grp1 = r"a(bc)(d(e)f)" grp2 = r"(?P<fi>abcd)(?:def)(ghi) #?P<fi> = abcd에fi검색tag부착 #def 는 group count 증가 X grp3 = r"gr(a|e)y" #gray 혹은 grey re.match(grp, "abcdefghijk") print(match.group(0)) #abcdefghijk print(match.group(1)) #bc
grp1 = r"a(bc)(d(e)f)" 
grp2 = r"(?P<fi>abcd)(?:def)(ghi)         #?P<fi> = abcd에fi검색tag부착
                                          #def 는 group count 증가 X 
grp3 = r"gr(a|e)y"                        #gray 혹은 grey  

re.match(grp, "abcdefghijk")              
print(match.group(0))                     #abcdefghijk
print(match.group(1))                     #bc  

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *