python을 프로젝트에서 사용하고 있어서
간단히 문법을 정리 해 둔다.
# osx에서 jupyter notebook을 실행
>sudo pip install jupyter
>jupyter notebook
# 문법 정리
# 문서 인코딩 지정
# -*- coding: utf-8 -*-
# 패키지(모듈) 포함시키기
import moduleName
from moduleName import functionName or className
from math import * # import all functions
from math import e
from math import e as newName # *e*를 새로운 이름 *newName*으로 사용
from math import (e, pi) # 복수로 포함하는 것을 나타내기 위해 괄호를 사용
# from을 사용하는 경우와 사용하지 않는 경우 차이
# from을 사용하면 모듈 이름을 생략할 수 있다.
import math
math.sin(60)
from math import sin
sin(60)
## 모듈 파일은 python 파일을 그대로 사용 가능
# 1. moduleName.py으로 함수 작성
# 2. import moduleName
# 코드 행을 도중에 바꿔서 계속 하고 싶을 때 : 코드 끝에서 「\」 (백슬래시) 사용
import urllib, poplib, sys, calendar, \
datetime, re
# 리터럴
b = 0b1000 # 2진수
c = 0x1ff # 16진수
# Boolean형
True
False
# Null값
None
# 대소문자 구별하기 때문에 변수 선언시 주의
python = 100
Python = 200
print(python, Python) #=> 100 200
# 표준 출력, 줄바꿈
print("abc")
print("abc", "def") # 공백을 두고 한줄에 표시
print("abc", file=sys.stderr) # 표준 오류로 출력
# 줄바꿈 없이 특정 문자로 연결 하여 출력하려고 할 때. end='{문자 or 문자열}'
for i in range(10):
print("abc", end = ' ') #=> abc abc abc abc abc abc abc abc abc abc
# 표준입력
s = input() # python3.x에서 raw_input() 삭제
print(s)
# 사칙연산
x += 1
x -= 1
x *= 1
x /= 1
x = 2 ** 10 # 지수 연산
x = 3 / 2 # 나눗셈 : 실수
x = 3 // 2 # 나눗셈 : 정수
x = 5 % 3 # 나머지
# python에 없는 연산자
# x++
# x--
# 문자열
s = "abc'def"
s = 'abc"def'
s = r'\d+\s\n' # raw문자열로 취급
# 문자열 조작
"abcdef"[0])
"abcdef"[0] = "x" # => 오류
"abcdef"[-1]
"abcdef".title()
"abcdef".lower()
"abcdef".upper()
"abcdef".endswith('f')
"abcdef".startswith('a')
"abcdef".strip()
"abcdef".count('c')
"abcdef" + "ghijkl"
"abcdef" * 3
"abcdef".replace("abc","replaced")
# 문자열에서 문자{열} 검색
"abcdef".find('x') #=> -1
"abcdef".index('x') #=> 오류
# 문자열 정렬
# 문자열 분할, 결합
# 문자열 길이
len("abcdef")
# ASCII 코드 관련 처리
ord("a") # 주어진 문자의 ASCII 코드값
chr(52) # 주어진 ASCII 코드값의 문자
# 문자열 내에 문자 포함 확인
if "a" in "abcdef":
do_something()
# 문자열 포멧
"{0} {1} {0}".format("Mika", "Mike")
"{name0} {name1} {name0}".format(name0="Mika", name1="Mike")
# 문법 정리
# 문서 인코딩 지정
# -*- coding: utf-8 -*-
# 패키지(모듈) 포함시키기
import moduleName
from moduleName import functionName or className
from math import * # import all functions
from math import e
from math import e as newName # *e*를 새로운 이름 *newName*으로 사용
from math import (e, pi) # 복수로 포함하는 것을 나타내기 위해 괄호를 사용
# from을 사용하는 경우와 사용하지 않는 경우 차이
# from을 사용하면 모듈 이름을 생략할 수 있다.
import math
math.sin(60)
from math import sin
sin(60)
## 모듈 파일은 python 파일을 그대로 사용 가능
# 1. moduleName.py으로 함수 작성
# 2. import moduleName
# 코드 행을 도중에 바꿔서 계속 하고 싶을 때 : 코드 끝에서 「\」 (백슬래시) 사용
import urllib, poplib, sys, calendar, \
datetime, re
# 리터럴
b = 0b1000 # 2진수
c = 0x1ff # 16진수
# Boolean형
True
False
# Null값
None
# 대소문자 구별하기 때문에 변수 선언시 주의
python = 100
Python = 200
print(python, Python) #=> 100 200
# 표준 출력, 줄바꿈
print("abc")
print("abc", "def") # 공백을 두고 한줄에 표시
print("abc", file=sys.stderr) # 표준 오류로 출력
# 줄바꿈 없이 특정 문자로 연결 하여 출력하려고 할 때. end='{문자 or 문자열}'
for i in range(10):
print("abc", end = ' ') #=> abc abc abc abc abc abc abc abc abc abc
# 표준입력
s = input() # python3.x에서 raw_input() 삭제
print(s)
# 사칙연산
x += 1
x -= 1
x *= 1
x /= 1
x = 2 ** 10 # 지수 연산
x = 3 / 2 # 나눗셈 : 실수
x = 3 // 2 # 나눗셈 : 정수
x = 5 % 3 # 나머지
# python에 없는 연산자
# x++
# x--
# 문자열
s = "abc'def"
s = 'abc"def'
s = r'\d+\s\n' # raw문자열로 취급
# 문자열 조작
"abcdef"[0])
"abcdef"[0] = "x" # => 오류
"abcdef"[-1]
"abcdef".title()
"abcdef".lower()
"abcdef".upper()
"abcdef".endswith('f')
"abcdef".startswith('a')
"abcdef".strip()
"abcdef".count('c')
"abcdef" + "ghijkl"
"abcdef" * 3
"abcdef".replace("abc","replaced")
# 문자열에서 문자{열} 검색
"abcdef".find('x') #=> -1
"abcdef".index('x') #=> 오류
# 문자열 정렬
print("abcdef".ljust(10,"*")) # 좌측 정렬. 빈 공간에는 주어진 문자로 채움
print("abcdef".rjust(10,"*")) # 우측 정렬
print("abcdef".center(10,"*")) # 중앙 정렬
print("abc def".split(" ")) # 주어진 문자를 기준으로 문자열 분리
print(" ".join(["abc","def"])) # 주어진 문자를 기준으로 리스트로 주어진 문자열을 결합
len("abcdef")
# ASCII 코드 관련 처리
ord("a") # 주어진 문자의 ASCII 코드값
chr(52) # 주어진 ASCII 코드값의 문자
# 문자열 내에 문자 포함 확인
if "a" in "abcdef":
do_something()
# 문자열 포멧
"{0} {1} {0}".format("Mika", "Mike")
"{name0} {name1} {name0}".format(name0="Mika", name1="Mike")
## 문자열 패딩, 왼쪽 정렬(<), 오른쪽 정렬(>), 중앙 정렬(^)
"{name0:<10} {name1:>10} {name2:^20}".format(name0="left", name1="right", name2="center")
"{:*^20s}".format("center") # 문자열을 중앙 정렬하며 빈 공간을 *문자로 채움
"{:.2%}".format(6260 / 12776) # %表記
# 값 교환 식
b, a = a, b
# 줄바꿈을 포함하는 문자열 사용할 때 「"""」 or 「'''」 문자로 선언
"{:.2%}".format(6260 / 12776) # %表記
# 값 교환 식
b, a = a, b
# 줄바꿈을 포함하는 문자열 사용할 때 「"""」 or 「'''」 문자로 선언
lines = '''
예제처럼
줄바꿈을 포함하는
문자열을 만들 수 있다.
문자열에서 줄바꿈을 포함하지 않는 경우는 \
예제처럼
줄바꿈을 포함하는
문자열을 만들 수 있다.
문자열에서 줄바꿈을 포함하지 않는 경우는 \
백슬래시(\) 문자를 붙이면 된다.
'''
# ()를 사용해서 「,」 없이 하나의 문자열을 선언할 수 있다.
lines = ("aaaaaa"
"bbbbb"
"ccccc")
# 조건연산(3항 연산자)
print("odd" if x % 2 is 1 else "even")
s = "odd" if x % 2 is 1 else "even"
# 형변환
int("123")
hex(1023)
bin(15)
oct(7)
float("1.3")
str(123)
tuple([1,2,3])
list((1,2,3))
# 진수 변환
int("0x100", 16)
int("0b1111", 2)
int("0o1777", 8)
# bit연산
x | y # or
x & y # and
x ^ y # xor
x << y # left shift
x >> y # right shift
# 함수
def functionname(x):
"""
함수 코멘트
"""
def do_something()
return result
def moveTo(x,y=0): # 파라미터에 기본값 선언
do_something()
moveTo(x=1, y=20) # 파라미터를 키워드로 전달
# 조건절 if
if s == "abc":
statementA()
elif s == "def":
statementB()
else:
statementC()
if min <= value <= max: # 비교연산자를 이렇게도 사용 가능
do_something()
# 복수의 반환값 전달
def foo():
minValue = 1
maxValue = 9
return minValue, maxValue
minValue, maxValue = foo()
(minValue, maxValue, ) = foo()
# 가변 파라미터
def foo(a, b, *vals):
print(a, b, vals)
foo(1, 2, 3, 4, "abc") # 1, 2, (3, 4, "abc")
# 가변 키워드 선언 변수
def foo(a, b, **args):
print(a, b, args)
foo(1, 2, key1=3, key2=4) # 1, 2, {'key1': 3, 'key2': 4}
# 조건연산자: 「==」 「!=」 「>」 「<」 「<=」 「>=」 「not in」 「in」
# 논리연산자: 「and」 「or」 「xor」
# switch는 사용할 수 없다
# 반복문
for i in range(6): # i = 0 to 5
print(i)
for i in range(1, 10, 2): # range(시작값, 종료값, 간격) i= 1,3,5,7,9
print(i)
# 반복 제어 명령 : continue, break
# While문
while 조건절:
do_something()
# do-while 은 사용할 수 없다.
'''
# ()를 사용해서 「,」 없이 하나의 문자열을 선언할 수 있다.
lines = ("aaaaaa"
"bbbbb"
"ccccc")
# 조건연산(3항 연산자)
print("odd" if x % 2 is 1 else "even")
s = "odd" if x % 2 is 1 else "even"
# 형변환
int("123")
hex(1023)
bin(15)
oct(7)
float("1.3")
str(123)
tuple([1,2,3])
list((1,2,3))
# 진수 변환
int("0x100", 16)
int("0b1111", 2)
int("0o1777", 8)
# bit연산
x | y # or
x & y # and
x ^ y # xor
x << y # left shift
x >> y # right shift
# 함수
def functionname(x):
"""
함수 코멘트
"""
def do_something()
return result
def moveTo(x,y=0): # 파라미터에 기본값 선언
do_something()
moveTo(x=1, y=20) # 파라미터를 키워드로 전달
# 조건절 if
if s == "abc":
statementA()
elif s == "def":
statementB()
else:
statementC()
if min <= value <= max: # 비교연산자를 이렇게도 사용 가능
do_something()
# 복수의 반환값 전달
def foo():
minValue = 1
maxValue = 9
return minValue, maxValue
minValue, maxValue = foo()
(minValue, maxValue, ) = foo()
# 가변 파라미터
def foo(a, b, *vals):
print(a, b, vals)
foo(1, 2, 3, 4, "abc") # 1, 2, (3, 4, "abc")
# 가변 키워드 선언 변수
def foo(a, b, **args):
print(a, b, args)
foo(1, 2, key1=3, key2=4) # 1, 2, {'key1': 3, 'key2': 4}
# 조건연산자: 「==」 「!=」 「>」 「<」 「<=」 「>=」 「not in」 「in」
# 논리연산자: 「and」 「or」 「xor」
# switch는 사용할 수 없다
# 반복문
for i in range(6): # i = 0 to 5
print(i)
for i in range(1, 10, 2): # range(시작값, 종료값, 간격) i= 1,3,5,7,9
print(i)
# 반복 제어 명령 : continue, break
# While문
while 조건절:
do_something()
# do-while 은 사용할 수 없다.
seq = {'key1': 3, 'key2': 4}
for loopCounter, item in enumerate(seq): # 루프카운터
print(loopCounter, item, seq[item])
# 2개의 리스트를 하나로 결합하여 반복문에 사용
for no, name in zip([1, 2, 3, 4], ['name1', 'name2', 'name3', 'name4']):
print(no, name)
# 예외 처리
try:
if condition:
raise Exception() # 예외를 생성
except Exception as e:
# 오류 처리
msg = "{1}(err={2})".format(e.errno, e.strerror)
sys.stderr.write(msg)
else:
# 예외가 발생하지 않는 경우 처리
finally:
# 후처리. 예외 발생과 관계 없이 마지막에 처리 됨
# with문 : 블럭 단위 실행을 효율적으로 실행. with문의 처리가 실패하면 블럭은 실행하지 않음
with open(fn) as f: # 이 구문이 실행 되면 블럭은 실행하지 않음
for line in f :
print(line)
## traceback으로 에외 처리
import traceback
try:
do_something()
except:
traceback.print_exc() # 예외 표시
message = traceback.format_exc() # 문자열 형태로
# 리스트
a = [1, 2, 3, 4, 5]
a[0]
a[-1] # 음수는 뒤에서부터 참조
a[5] # 범위 밖 참조는 오류
# 리스트 자르기:추출을 원하는 요소의 마지막 인덱스+1을 지정한다
a[1:3] #=> a[1] ~ a[3 - 1] 까지 추출 => [2, 3]
a[2:] #=> [3, 4, 5]
a[:3] #=> [1, 2, 3]
a[2:100] #=> [3, 4, 5]
a * 2 #=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
a + [6,7] #=> [1, 2, 3, 4, 5, 6, 7]
a[1] = "x" #=> [1, "x", 3, 4, 5, 6, 7]
del a[1] #=> [1, 3, 4, 5, 6, 7]
print(a.index(1))
if 1 in a:
print("1 in a")
max(a)
min(a)
a.sort() # 정렬
a.reverse() # 역으로 정렬
a.append(6) # 리스트에 데이터 추가
a.extend([6, 7, 8]) # 리스트 확장
a.remove(1) # 주어진 요소를 제거
a.pop(0) # 주어진 위치의 요소를 pop
# 다차원 행렬
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix[0][2]
# 튜플
# 변경 불가능한 리스트, dictionary형의 키로서 사용 가능
t = (1, 2, 3, 4, 5)
# 사용예
# Dictionary
dict = { "key1":"경기도", "key2":"강원도" }
dict["key1"]
# .get(key, default): 키가 없으면 오류 없이 None값 또는 default값을 반환
for word in lines.split():
wordcount[word] = wordcount.get(word, 0) + 1
dict["key1"] = "경상도"
del dict["key1"]
dict.keys()
dict.values()
dict.items() # key,value의 튜플 리스트 반환
if "key1" in dict:
do_something()
# dictionary 연결
dict1.update(dict2) # 같은 키의 경우 업데이트
# 집합set
ipmap = {(192,168,0,1):"host1.name.com",(192,168,0,2):"host2.name.com",}
print(ipmap[(192,168,0,1)]) # host1.name.com
# Dictionary
dict = { "key1":"경기도", "key2":"강원도" }
dict["key1"]
# .get(key, default): 키가 없으면 오류 없이 None값 또는 default값을 반환
for word in lines.split():
wordcount[word] = wordcount.get(word, 0) + 1
dict["key1"] = "경상도"
del dict["key1"]
dict.keys()
dict.values()
dict.items() # key,value의 튜플 리스트 반환
if "key1" in dict:
do_something()
# dictionary 연결
dict1.update(dict2) # 같은 키의 경우 업데이트
# 집합set
s = {1, 2, 3, 4}
s2 = {5, 6}
s.remove(7) # 키 오류
s.discard(7) # 오류 없음
# 집합에 요소 추가
s.add(7)
s |= {7}
if s == s2:
do_something()
if 1 in s:
do_something()
s.union(s2) # s | s2 합집합
s.intersection(s2) # s & s2 교집합
s.difference(s2) # s - s2 차집합
s.symmetric_difference(s2) # 합집합-교집합
# map(입력받은 각 요소에 대한 f함수의 결과를 반환한다. )
map1 = map(float, range(5))
# Null판단
if x is (not) None:
do_something()
# 파일 읽기
f = open("foo.txt", "r", encoding="utf-8")
s = f.read() # 전체 읽기
line = f.readline() # 1행 읽기
lines = f.readlines() # 전체 읽기
f.close()
# 파일 쓰기
f = open("foo.txt", "w", encoding="utf-8")
f.write(s)
f.writelines(seq) # 줄바꿈 문자는 포함하지 않는다. 추가를 해야 한다.
f.close()
# 리스트 내포 구문(List Comprehension)
sq = [x ** 2 for x in range(5)]
sq #=> [0, 1, 4, 9, 16]
## 조건절 추가
val = 10
[x for x in range(1,val) if val % x == 0] #=> [1, 2, 5]
filter2 = [x for x in ['cat','dog', 'bird'] if 'cat' in x]
filter2 #=> ['cat']
tz = {"GMT" : "+000", "BST" : "+100", "EET" : "+200", "JST" : "+900"}
revtz = {value : name for name, value in tz.items()}
revtz #=> {'+200': 'EET', '+100': 'BST', '+000': 'GMT', '+900': 'JST'}
names = ['BOB', 'Burton', 'dave', 'bob']
unames = {x.title() for x in names}
unames #=> {'Bob', 'Dave', 'Burton'}, 결과가 집합형이어서 BOB와 bob는 한개만 존재한다.
# 아무것도 하지 않고 통과 구문
pass
# 코드의 실행 시간 측정
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
# CLI의 파라미터 읽기
s2 = {5, 6}
s.remove(7) # 키 오류
s.discard(7) # 오류 없음
# 집합에 요소 추가
s.add(7)
s |= {7}
if s == s2:
do_something()
if 1 in s:
do_something()
s.union(s2) # s | s2 합집합
s.intersection(s2) # s & s2 교집합
s.difference(s2) # s - s2 차집합
s.symmetric_difference(s2) # 합집합-교집합
# map(입력받은 각 요소에 대한 f함수의 결과를 반환한다. )
map1 = map(float, range(5))
# Null판단
if x is (not) None:
do_something()
# 파일 읽기
f = open("foo.txt", "r", encoding="utf-8")
s = f.read() # 전체 읽기
line = f.readline() # 1행 읽기
lines = f.readlines() # 전체 읽기
f.close()
# 파일 쓰기
f = open("foo.txt", "w", encoding="utf-8")
f.write(s)
f.writelines(seq) # 줄바꿈 문자는 포함하지 않는다. 추가를 해야 한다.
f.close()
# 리스트 내포 구문(List Comprehension)
sq = [x ** 2 for x in range(5)]
sq #=> [0, 1, 4, 9, 16]
## 조건절 추가
val = 10
[x for x in range(1,val) if val % x == 0] #=> [1, 2, 5]
filter2 = [x for x in ['cat','dog', 'bird'] if 'cat' in x]
filter2 #=> ['cat']
tz = {"GMT" : "+000", "BST" : "+100", "EET" : "+200", "JST" : "+900"}
revtz = {value : name for name, value in tz.items()}
revtz #=> {'+200': 'EET', '+100': 'BST', '+000': 'GMT', '+900': 'JST'}
names = ['BOB', 'Burton', 'dave', 'bob']
unames = {x.title() for x in names}
unames #=> {'Bob', 'Dave', 'Burton'}, 결과가 집합형이어서 BOB와 bob는 한개만 존재한다.
# 아무것도 하지 않고 통과 구문
pass
# 코드의 실행 시간 측정
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
# CLI의 파라미터 읽기
import sys
for arg in sys.argv[1:] # argv[0]=파이썬 스크립트 이름
print(arg)
# 이터레이터
i = iter([1, 2, 3]) # 이터레이터 객체로 변환
next(i) # 다음 요소를 읽기, 요소가 없다면 StopIteration예외 발생
## 파일 읽기를 아래와 같이 처리 가능
for line in open("test.txt", "r", encoding="utf-8"):
print(line, end=" ")
# 제너레이터 : 이터레이터 같은 기능을 내부에 구현
# yield문을 사용
# 제너레이터 형식으로 사용
gen = (ord(s) for s in 'Python')
next(gen)
for code in (ord(s) for s in 'Python'):
print(code)
# 람다식 사용 가능
fx = lambda x: x * 10
# CLI의 메인으로 실행 될 때만 실행하도록 할 때 사용
if __name__ == '__main__':
do_something()
# 클래스 정의와 인스턴스 생성
class Person(SuperClassName):
def __init__(self, name, age): # 생성자 선언, 초기값 사용
self.name, self.age = name, age
self.address = None
bob = Person('Bob', 15)
print bob.name
bob.address = 'USA'
## 클래스 상송 (다중 상속 가능)
class Person(SuperClassName):
def __init__(self, width):
super(Person, self).__init__() # 부모 클래스의 생성자 호출
self.width = width
# 속성(인스턴스 변수) 과 클래스 변수 차이
# 메소드와 속성의 캡슐화는 이름 앞에 __를 붙인다.
for arg in sys.argv[1:] # argv[0]=파이썬 스크립트 이름
print(arg)
# 이터레이터
i = iter([1, 2, 3]) # 이터레이터 객체로 변환
next(i) # 다음 요소를 읽기, 요소가 없다면 StopIteration예외 발생
## 파일 읽기를 아래와 같이 처리 가능
for line in open("test.txt", "r", encoding="utf-8"):
print(line, end=" ")
# 제너레이터 : 이터레이터 같은 기능을 내부에 구현
# yield문을 사용
def city_generator():
yield("London")
yield("Hamburg")
yield("Konstanz")
yield("Amsterdam")
yield("Berlin")
yield("Zurich")
yield("Schaffhausen")
yield("Stuttgart")
city = city_generator()
while True:
print(next(city))
## 피로나치 수열을 제너레이터로 구현
def fibonacci(n):
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5)
for x in f:
print(x, " ", end="") #
print()
# 제너레이터 형식으로 사용
gen = (ord(s) for s in 'Python')
next(gen)
for code in (ord(s) for s in 'Python'):
print(code)
# 람다식 사용 가능
fx = lambda x: x * 10
# CLI의 메인으로 실행 될 때만 실행하도록 할 때 사용
if __name__ == '__main__':
do_something()
# 클래스 정의와 인스턴스 생성
class Person(SuperClassName):
def __init__(self, name, age): # 생성자 선언, 초기값 사용
self.name, self.age = name, age
self.address = None
bob = Person('Bob', 15)
print bob.name
bob.address = 'USA'
## 클래스 상송 (다중 상속 가능)
class Person(SuperClassName):
def __init__(self, width):
super(Person, self).__init__() # 부모 클래스의 생성자 호출
self.width = width
# 속성(인스턴스 변수) 과 클래스 변수 차이
class A:
attr1 = 1
attr2 = 2
def __init__(self):
self.a = 1
self.b = 2
test1 = A()
test2 = A()
test1.a = 3
test1.b = 4
test2.c = 5 # => test2 인스턴스 속성으로 추가 된다.
A.attr1 = 10 # => 전체 인스턴스에 반영된다.
print(test2.attr1)
print(test1.attr1)
print(vars(test1))
print(test1.attr1)
print(A.attr1)
print(vars(test2))
# 메소드와 속성의 캡슐화는 이름 앞에 __를 붙인다.
class A:
def __init__(self):
self._size1 = 10
self.__size2 = 10
obj = A()
print(obj._size1) # 인스턴스 변수로 접근 가능
print(obj.__size2) # 인스턴스 변수로 접근 불가능
print(obj._size1) # 인스턴스 변수로 접근 가능
print(obj.__size2) # 인스턴스 변수로 접근 불가능
obj.__size2 = 100 # 생성자에서 선언한 self.__size2 와 다른 변수
print(vars(obj)) # 차이를 알 수 있다.
## Setter / Getter : 데이터 변경/참조하는 전용 메소드
## 인스턴스 변수(프로퍼티)처럼 사용
__sub__(self, other) # -
__mul__(self, other) # *
__truediv__(self, other) # /
__floordiv__(self, other) # //
__iadd__(self, other) # +=
__isub__(self, other) # -=
__imul__(self, other) # *=
__itruediv__(self, other) # /=
__ifloordiv__(self, other) # //=
__or__(self, other) # | (or)
__and__(self, other) # & (and)
## 비교연산자 오퍼레이터
## equal, not equal, lesser than, greater than, ...
__eq__(self, other) # ==
__ne__(self, other) # !=
__lt__(self, other) # < (self < other)
__gt__(self, other) # >
__le__(self, other) # <=
__ge__(self, other) # >=
## 형변환 오퍼레이터
__int__(self) # int()
__bytes__(self)
__float__(self)
__str__(self)
__repr__(self) # 문자열 형식으로 변환
__format__(self, form_spec) # format()함수 재정의
## 객체의 형 판단
isinstance(var, type) # 판정(type= str, int, float, ...)
## Setter / Getter : 데이터 변경/참조하는 전용 메소드
## 인스턴스 변수(프로퍼티)처럼 사용
class Prop(object):
def __init__(self):
self.__x = 0
def getx(self): # Getter
return self.__x
def setx(self, x): # Setter
self.__x = x
x = property(getx, setx) # 프로퍼티 x의 getter/setter 로 설정
def check(self):
return self.__x
i = Prop()
i.x = 10000
print("i.x=",i.x)
print("i.__x=",i.check())
print(vars(i))
## 연산자 오퍼레이터. 재정의 할 때 사용
__add__(self, other) # + (self + other)__sub__(self, other) # -
__mul__(self, other) # *
__truediv__(self, other) # /
__floordiv__(self, other) # //
__iadd__(self, other) # +=
__isub__(self, other) # -=
__imul__(self, other) # *=
__itruediv__(self, other) # /=
__ifloordiv__(self, other) # //=
__or__(self, other) # | (or)
__and__(self, other) # & (and)
## 비교연산자 오퍼레이터
## equal, not equal, lesser than, greater than, ...
__eq__(self, other) # ==
__ne__(self, other) # !=
__lt__(self, other) # < (self < other)
__gt__(self, other) # >
__le__(self, other) # <=
__ge__(self, other) # >=
## 형변환 오퍼레이터
__int__(self) # int()
__bytes__(self)
__float__(self)
__str__(self)
__repr__(self) # 문자열 형식으로 변환
__format__(self, form_spec) # format()함수 재정의
## 객체의 형 판단
isinstance(var, type) # 판정(type= str, int, float, ...)