반응형

python file i/o, directory, read/write

-파일 IO

파일객체=open(file, mode)

간략하게
f = open('a.txt') 이렇게도 된다.

-mode 
r ; read (default)
r+ ; read/write
w ; write
a    ; append
t    ; text mode (default)
b ; binary

contents=f.read()    ; 전체 읽기
str=f.readline()    ; 한 줄 읽기 (\n포함!), 더 읽을게 없으면 None 리턴.
strarray=f.readlines() ; 여러줄을 읽어 list로 반환. (\n포함!)

f = open('filename', 'mode')
while 1:
     line = f.readline()    # 마지막에 \n도 포함되어 줄 단위로 읽는다.
     if not line : break
     print(line)
f.write(buf)
f.close()

여러줄 읽기
lines = f.readlines()
tell(), seek() 지원



+ 파일 열기
f = open('c:\\users\\user01\\desktop\\a.txt', 'rt')
     오픈 모드 ; r=read, w=write
               t=text, b=binary
+ 읽기
lines = f.readlines()          # 여러줄 읽기. string list로 반환. (마지막에 \n도 포함됨.)                                     제거하려면, rstrip() 사용
f.close()

for line in lines:
     print(line, end="")     # 라인마지막에 \n이 포함되어 있어서 print에서 자체 \n을 제거하여 출력.


-파일 IO

파일객체=open(file, mode)
간략하게
f = open('a.txt') 이렇게도 된다.

-mode ; 
r ; read (default)
r+ ; read/write
w ; write
a    ; append
t    ; text mode (default)
b ; binary

f.read()    ; 전체 읽기
f.readline()    ; 한 줄 읽기 (\n포함), 더 읽을게 없으면 None 리턴.
f.readlines() ; 여러줄을 읽어 list로 반환. (\n포함)

f = open('filename', 'mode')
while 1:
     line = f.readline()    # 마지막에 \n도 포함되어 줄 단위로 읽는다.
     if not line : break
     print(line)
f.write(buf)
f.close()
모드는 r,w,a
여러줄 읽기
lines = f.readlines()
tell(), seek() 지원



+ 파일 열기
f = open('c:\\users\\user01\\desktop\\a.txt', 'rt')
     오픈 모드 ; r=read, w=write
               t=text, b=binary

+ 읽기
lines = f.readlines()          # 여러줄 읽기. string list로 반환. (마지막에 \n도 포함됨.) 제거하려면, rstrip() 사용
f.close()

for line in lines:
     print(line, end="")     # 라인마지막에 \n이 포함되어 있어서 print에서 자체 \n을 제거하여 출력.

+쓰기
f = open('a.txt', 'wt')
f.write('test\n')
f.write('test2\n')
f.close()

f.seek(위치)
f.tell()    ; 현재 위치

f = open('a.txt', 'wt')
f.write('test\n')
f.write('test2\n')
f.close()

f.seek(위치)
f.tell()    ; 현재 위치






+ OS, sys 모듈

import os
               print (os.getcwd())          ; 현재 디렉터리
os.listdir('c:\python27')        ; dir list
os.rename('a.txt', 'b.txt')     ; rename file
os.chdir('/users/...')          ; cd

os.path.join('/users/aa', 'a.py')          ; 경로 만들기
os.path.expanduser('~')     ; home dir
(dirname, filename) = os.path.split(pathname)          ; directory, filename 분리
(shortname, ext) = os.path.splitext(filename)               ; filename, extension 분리 ; 
abc.py -> abc, .py



++ 현재 소스 디렉터리

srcdir = os.path.dirname( os.path.abspath(__file__))

print('srcdir=', srcdir)



+ listing directory          
import glob                              ; glob module ; shell wild card support!
glob.glob('examples/*.xml')         ; 파일 목록 조회


+ file info
metadata = os.stat('feed.xml')
metadata.st_mtime
123332323.32233223
time.localtime(metadata.st_mtime)     ; time.struct_time( tm_year, tm_mon, tm_mday, tm_hour, tm_min...)
metadata.st_size     ; file size

import humansize
humansize.approximate_size( metadata.st_size)     ; '3.0 KiB'

-전체 경로 얻기
os.path.realpath('feed.xml')          ; full path

os.getcwd() ; 현재 디렉터리
os.chdir(…) ; 현재 디렉터리 이동

os.path.isdir(...)     
os.path.isfile(...)     ; 존재여부 & 파일타입
os.path.isexists(...) ; 존재 여부
os.path.getsize(...)  ; 파일 크기
os.path.split(...')     ; (dir, file) 두 부분으로 잘라준다. 두 부분을 나누는 delimeter는 제외.
os.path.join(dir,filename) ; 두 개를 합쳐준다.
os.sep    ; os seperator 문자. / or \
os.path.normpath(mixed) ; / 와 \가 섞였을때 고쳐준다.

os.getpid()     ; process id
os.getuid()     ; process's real user id
os.getlogin()     ; user id
os.mkdir('c:\\test\\test1\\test2')     ; mkdir(path [,mode])     default mode = 0777, if exist? OSError.

os.makedirs(path[, mode]) ; 중간 경로 생성. if exist, error.  에러 무시하려면?      exist_ok=True를 추가함.
os.makedirs('c:\\test\\test1\\test2', exist_ok=True)




반응형

[Python에서 API서비스 구현하기]


POST로 JSON 요청받아 작업쓰레드를 돌려서 비동기 방식으로 작업하고,

진행 상태를 체크할 수 있는 구조.

Flask 사용.



- 구동 쉘 스크립트 ; server_run.sh

#!/bin/bash
/opt/anaconda3/envs/tensorflow/bin/python server_learn.py

- 서버 ; server_learn.py


from flask import Flask, request
from flask_restful import Resource, Api
from flask.views import MethodView
import json, base64
import string
import random
import os
import threading, time

app = Flask(__name__)
api = Api(app)

# 랜덤스트링 생성하는 함수. 세션키 생성 등
def random_string(size=6, chars=string.ascii_lowercase+string.digits):
return ''.join(random.choice(chars) for _ in range(size))


# 글로벌
g_bworking=False    # 작업 여부.
g_progress = 0        # 진행 상태. 0~100
g_elapsedtime = 0    # 소요 시간. sec
g_workresult={}    # 작업 결과
g_workname=''       # 작업명

# 워커 쓰레드 ; 1~p1까지 sum구하기. 루프 돌때마다 p2 sec만큼 sleep.
def work(myid, p1, p2):
global g_bworking, g_progress, g_workresult, g_elapsedtime
starttime = time.time()

if g_bworking==True:
print('server is busy...')
return 0
g_bworking=True
g_workresult={}
g_progress=0
g_elapsedtime=0
total = 0
for i in range(1, (p1+1)):
total+=i
time.sleep(p2)
print('work : total[',myid,'] = ', total)

g_progress = 100* i / (p1)
g_elapsedtime = time.time() - starttime


endtime = time.time()
g_elapsedtime = endtime - starttime
g_workresult={'total':total, 'until':p1, 'sleep': p2}
g_progress=100
g_bworking=False
return total


class mysum(MethodView):
def get(self):
data = request.args
print(data) # dictionary
return {'name':'test'}

def options(self):
print('options.')
data = request.get_json() # application/json
print(data)
return {'Allow':'PUT,GET,POST'}, 200, \
{'Access-Control-Allow-Origin': '*', \
'Access-Control-Allow-Headers':'Content-Type,Authorization',\
'Access-Control-Allow-Methods': 'PUT,GET,POST'}

def post(self):
global g_workname
# data = request.form
# print(data) # dictionary
data = request.get_json() # application/json
print(data)

if g_bworking==True:
LearnResult = { 'result': 0 }
else:
num = int(data['num'])
slp = int(data['slp'])
g_workname = data['name']
t = threading.Thread(target=work, args=(g_workname, num, slp))
t.start()
LearnResult = {
'result': 1
}
return LearnResult


class status(MethodView):
def get(self):
data = request.args
print(data) # dictionary
if g_progress > 0 :
predtime = g_elapsedtime * 100 / g_progress
else:
predtime = 0
result = { 'work':int(g_bworking),
'workname':g_workname,
'progress':str(g_progress),
'workresult': g_workresult,
'elapsedtime':str(g_elapsedtime),
'remaintime': str(predtime - g_elapsedtime) }
return result

api.add_resource(mysum, '/mysum')
api.add_resource(status, '/status')

if __name__=='__main__':
app.run(host='0.0.0.0', port=18899, debug=True)


- 테스트

http://127.0.0.1:18899/mysum

POSTDATA ; 1~10까지 합 요청. 단계별로 1초씩 쉼.

{

    "num": "10",

    "slp": "1",

    "name": "work1"

}

response: 즉시 아래와 같이 성공 리턴됨.

{

    "result": 1

}



http://127.0.0.1:18899/status

GET

주기적으로 상태 체크 API 호출하여 결과 확인.

{

    "workresult": {

        "until": 10,

        "total": 55,

        "sleep": 1

    },

    "remaintime": "0.0",

    "workname": "work1",

    "elapsedtime": "10.011629581451416",

    "work": 0,

    "progress": "100"

}









반응형

HTML 파싱하여 원하는 부분 추출하기.


+ Beautifulsoup 설치

pip install beautifulsoup4
버전 4


+ URL로 HTML 가져와서파싱하기
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

url="http://www.naver.com/"
html = urlopen(url).read()

soup = BeautifulSoup(html, 'html.parser')

rank = soup.find("dl", id="ranklist")     # dl tag, id=ranklist search.

for i in rank.find_all("li", value=True, id=False):          # li tag, value exist, id no exist. search
     print( i.get_text(" ", strip=True) )  # 문자열을 가져오는데, 태그는 공백으로 두고, 앞뒤 공백 제거.


+헤더 추가
req = Request(url)
req.add_header('User-Agent', 'Mozilla/5.0')
html = urlopen(req).read()



+BeautifulSoup html 서치.

-모든 태그 검색
html_as=soup.find_all("a")     # 모든 a 태그 검색. 접근시 html_as[0], [1], .. 첫번째가 0인덱스.
soup("a")     # 상동

-스트링이 있는 title 태그 모두 검색
soup.title.find_all(string=True)
soup.title(string=True)

-a태그 두 개만 가져옴.
soup.find_all("a", limit=2)

-스트링 검색
soup.find_all(string="elsie")   해당 스트링 검색
 or검색을 하려면 array 로 입력 ["aa", "bb"]
 정규식을 쓰려면 re.compile("정규식")

-태그와 속성(클래스)값으로 검색
soup.find_all("p", "title")
soup.select('p[class="title"]')
ex) <p class="title"></p>

-태그와 태그 사이 찾기
soup.find_all(["a", "b"])

-속성(클래스)값 가져오기
soup.p['class']
soup.p['id']

-보기 좋게 출력
soup.b.prettify()


-검색
soup.body.b     각 첫번째 노드
soup.a     # 처음으로 나오는 a태그

-태그와 클래스명 검색
soup.find_all("a", class_="sister")     # class_ 를 사용. 예약어라서 _를 사용.

-태그와 ID로 찾기
soup.find("div", id="articlebody")
soup.find("div", { "id":"articlebody" } )
soup.find(id="articlebody")

soup.select("#articlebody") ; id로 검색.
soup.select("div#articlebody") ; 태그와 id로 검색.

-태그와 클래스로 찾기 
soup.select('div ol[class="list1"]')

find_all 이나 select는 array로 리턴. 복수개!
하나만 찾을 때는 find 사용.


-검색결과 없으면 None

-태그의 이름 얻기
soup.find("div").name

-속성 얻기
soup.find("div")['class']          없으면 에러
soup.find("div").get('class')     없으면 None


-태그 사이에 있는 중간의 텍스트 얻기
contents 속성 사용.
<p> aaa
<b> one </b>
cc
</p>

soup.b.string          ==> one
soup.b.contents[0]     ==> one

soup.p.contents     ==> aaa, <b>one</b>, cc
     원하는 원소 인덱스를 사용.

-다음 형제 태그
soup.p.next_sibling

-태그 내부 추적 검색
ptag = soup.p
ptag('table')[0]('tr')[0]('td')[0]

-태그 사이 텍스트 전체 
ptag.get_text()




+ HTML 파일에서 읽기
import codecs

page_html = codecs.open('a.html''r''utf-8')
page_soup = soup(page_html, "html.parser")

+태그 추적하기 
예)

// span 태그의 아이디로 먼저 검색하고, 자식중에 2번째 table 태그를 찾음.
testwebsite_container = page_soup.find("span"id="MainContent2_ctl00_lblContent").findAll("table")[1]

skiptrcnt=1 # skip first tr block
for i,record in enumerate(testwebsite_container.findAll('tr')):    # 모든 tr태그를 검색.
    if skiptrcnt>i:
        continue
    # 처음 n개는 스킵한다.
tnum = record('td')[0].text        # 첫 번째 td의 텍스트
desc = record('td')[1].text
doclink = record('td')[2].text    #세번째 td의 텍스트 (a link의 보이는 링크명으로 보이는 부분이 나옴.)
alink = record('td')[2].find("a")       # 세번째  td에서 하위에 a태그를 찾음.
if alink :
    doclinkurl=testwebsite+alink['href'   # 속성! href의 값을 가져온다. 
closingdate = record('td')[3].text

detail = record('td')[4].text            # td태그 내부에 br태그가 있으면 줄바뀜이 생김.
detail = detail.replace('\n''')        # 줄바뀜 제거. 











'Python' 카테고리의 다른 글

File I/O, Directory list, read/write  (0) 2018.07.04
WebAPI thread work status  (0) 2018.07.03
Python 데이터 저장/로딩 Pickle  (0) 2018.04.25
Python 커맨드라인 파싱  (0) 2018.04.17
Python 쉘 커맨드 실행  (0) 2018.04.12
반응형


파이썬은 자료 구조를 쉽게 파일로 저장 및 로딩할 수 있다.


+ Pickle : Save & Load        데이터 저장/로딩

주의! 저장한 순서대로 로딩해야 한다.


- pickle 모듈 사용

저장 파일이 있으면 로딩하고, 없으면 저장하는 샘플.

import os, pickle

savefile='mnist.pkl'
if os.path.exists(savefile) :
    print('loading from cache...')
    f = open(savefile, 'rb')
    x_train = pickle.load(f)
    x_test =  pickle.load(f)
    f.close()
else:
    print('downloading.. MNIST..')
    (x_train,_), (x_test, _) = mnist.load_data()
    f = open(savefile, 'wb')
    pickle.dump(x_train, f)
    pickle.dump(x_test, f)
    f.close()


'Python' 카테고리의 다른 글

WebAPI thread work status  (0) 2018.07.03
Python BeautifulSoup 웹크롤링/HTML 파싱.  (0) 2018.04.25
Python 커맨드라인 파싱  (0) 2018.04.17
Python 쉘 커맨드 실행  (0) 2018.04.12
Python JSON 사용하기  (0) 2018.04.10
반응형




+ 커맨드 라인으로 파이썬 파라미터 주기
$python test.py arg1 arg2 arg3

import sys
len(sys.argv) => 4
str(sys.argv) => ['test.py', 'arg1', 'arg2', 'arg3']

C 방식과 동일.


+ 커맨드 라인 파싱 모듈

test.py -h               ; short option. 추가 파라미터 필요없음.
test.py -i <inputfile> -o <outputfile>          ; short option
test.py --ifile=<inputfile> --ofile=<outputfile>          ; long option

short option은 -한문자로 구성. 데이터는 뒤에 파라미터를 사용.
long option은 --스트링으로 구성 데이터는 =으로 받음.

import sys, getopt

main(sys.argv[1:]) ; 현재 파일명 이후의 파라미터목록을 전달.

def main(argv)
try:
     opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
except getopt.GetoptError:
     print('사용법')
     sys.exit(2)

for opt, arg in opts:
     if opt=='-h':
          #to do
          sys.exit(2)
     elif opt in ("-i", "--ifile"):
          infile=arg
     elif opt in ("-o", "--ofile"):
          outfile=arg

-------------------------------------------------------------------------------------
opts, args = getopt(파라미터 array,   "short option", [long options] )

short option은  사용할 문자들을 준다.  옵션뒤에 추가파라미터가 필요하면 문자뒤에 :을 추가.
hi:o:    ==> i와 o 옵션은 뒤에 파라미터 필요. h는 불필요.

long option은 =으로 끝나게 주면 된다.
"ifile=", "ofile="

opt, arg쌍으로 opts에서 가져온다.
옵션이름은 실제 스트링값을 사용. -h, -i, -o, --file, --ofile





반응형



+ 쉘 커맨드 실행하기.

1. os.system 구문을 이용해 명령 실행 하기
import os
import sys
os.system ('ls -al | grep "user")

// pipe command is available
위와 같이 단순히 명령 실행을 위해 사용시에는 문제가 없으나,
결과값을 특정 변수에 저장하는 목적으로 사용하기에는 적합하지 않다.
(명령 실행 결과의 성공 유무를 리턴하기 때문에…)
따라서 위의 단점을 보완할 수 있는 방법이 바로 subprocess 이다.

2. subprocess 이용하여 명령 실행하기
먼저 os.system과 같이 단순히 “실행”만 시킬 때는 “call” 메서드를 이용하면된다.

import subprocess
subprocess.call ('ls -al', shell=True)
그러나 특정 명령 수행 결과를 바탕으로 if 조건문을 걸때에는 call이 아닌 check_ouput을 이용해야 한다.

예를들어 특정 파일 실행결과가 “AAA” 혹은 “BBB”라고 가정해보자.
“AAA” 일 경우 “123”을 출력하고 “BBB”일 때 “456”을 출력하려면 다음과 같이 코드를 작성하면 된다

import subprocess
result = subprocess.check_output ('./program' , shell=True)
if result == 'AAA' :
  print "123"
elif result == 'BBB' :
  print "456"
위와 같이 check_output 메서드를 사용하면 해당 실행 결과를 스트링값으로 리턴해주기 때문에

실제 실행결과값을 바탕으로 조건 구문을 사용할 수 있게 된다.

 


'Python' 카테고리의 다른 글

Python 데이터 저장/로딩 Pickle  (0) 2018.04.25
Python 커맨드라인 파싱  (0) 2018.04.17
Python JSON 사용하기  (0) 2018.04.10
Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌7 클래스  (0) 2018.03.27
반응형





+JSON
기본으로 설치되어 있다.
import json

-JSON 인코딩
customer={ 'id':111, 'name':'james',
    'history':[ {'date':'2015-01-01', 'item':'iphome'}, {'date':'2016-01-01', 'item':'android'}]
}
jsonString = json.dumps(customer)    # JSON 스트링으로 변환

출력
print(jsonString)

보기 좋게 출력하려면 인코딩시 indent 추가
jsonString = json.dumps(customer, indent=4)

-JSON 디코딩
JSON 스트링을 Python 객체로
dict = json.loads(jsonString)
dict['name']
dict['history'][0]['date']
for h in dict['history']:
    print(h['date'], h['item'])

 


'Python' 카테고리의 다른 글

Python 커맨드라인 파싱  (0) 2018.04.17
Python 쉘 커맨드 실행  (0) 2018.04.12
Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌7 클래스  (0) 2018.03.27
Python 강좌6 tuple, set, dictionary  (0) 2018.03.21
반응형




모듈 Module


+ 외부 모듈 가져오기 (import)
import시 찾는 경로를 알기 위해서는 아래와 같이 path를 찾아본다.
import sys
sys.path
PATH 추가
sys.path.insert(0, ‘/home/…’)   첫 번째 path에 추가한다.

import 모듈      ; 모듈 전체 가져오기. 사용시 모듈.변수 등으로 사용.
or
from 모듈 import 변수나 함수  ; 모듈의 특정 부분만 가져오기.
import한 모듈을 더 이상 사용 안할 경우
del 모듈
다시 불러오기
reload 모듈

import math
dir(math)          # math에 정의되어 있는 함수, 변수등을 확인.
math.sin(90)
math.row(2,10)
math.pi

+ 모듈의 정의
arithmetic.py라고 파일이름을 만들어 여러가지 함수들을 만든다.

import arithmetic
dir(arithmetic)
arithmetic.plus(1,2)
arithmetic.mul(300,400)

현재 경로에 존재하지 않으면?
폴더 지정도 가능. 현재폴더 기준. mylib 폴더내에 arithmetic.py가 있다면...
from mylib.arithmetic import *


from arithmetic import plus     # 해당 파일의 특정 함수만 로딩.
plus(100,200)

from arithmetic import *     # 해당 파일에 있는 모든 함수 사용 가능.





+string 모듈

import string
string.captialize('python')
'Python'
string.replace('simple', 'i', 'a')
'sample'
string.split('break into words')
['break', 'into', 'words']

+webbrowser 모듈
import webbrowser
url='http://google.com'
webbrowser.open(url)

+random
import random
random.random()
0이상 1미만 소수
random.randrange(1,7)
1~6까지 정수.









+ with as
; try~finally 같은 역할.
특정 블록을 벗어날때 항상 처리되어야 할 것이 자동화 처리.
with open('filename', 'w') as f:
     f.write(something);
close()가 없어도 자동 처리.



+ 시간 time, date 날짜
import time
time.time()     ; 19700101이후누적 시간 (초). 소수점이하 포함.
time.ctime()    ;    Sun Oct 11 12:00:50 2015
time.gmtime()
time.localtime()

time.sleep(sec) ; millisec를 하려면, sec/1000.0으로 해줘야 함.


dir(time)    ; 모듈의 내장 함수 목록 조회.



+try, except
try… except  예외 처리.
자바와 c++에서는 try, catch를 사용하고, 예외 발생시 throw를 사용.
파이썬은 try, except를 사용하고, raise를 사용.

try:
     to do...
except:
     ignore....



if size<0:
    raise ValueError(‘number must be non-negative!’)



+try ~ except

try:
    구문
except <예외 종류>:
    예외 처리

try:
    a=10/0
except ZeroDivisionError:        # 잡을 예외
    print('divede by zero.')

try:
    a=int( input('input number:'))
except ValueError:
    print('invalid number!')
except ZeroDivisionError:            # 더 있으면 아래 계속 추가 가능.
    print('divide by zero!')

except (ValueError, ZeroDivisionError):        # 복수개를 한 번에 처리 가능.


+ else
try:
    ...
 except ...:
        ...
else:
    예외가 발생하지 않을 경우.

+ finally

finally:
    무조건 실행되는 영역

+raise
예외 발생

try:
    ...
    if a<=0 or b<=0:
        raise ArithmeticError('message...')
    except ArithmeticError as e:
        print( e.args[0] )
에러 메시지를 받아 출력...





+실행프로그램으로 현재 코드가 실행되는지 확인. (외부 임포트의 경우는 아래 코드가 실행되지 않음.)
if __name__==‘__main__’:
    print(…)





'Python' 카테고리의 다른 글

Python 쉘 커맨드 실행  (0) 2018.04.12
Python JSON 사용하기  (0) 2018.04.10
Python 강좌7 클래스  (0) 2018.03.27
Python 강좌6 tuple, set, dictionary  (0) 2018.03.21
Python 강좌5 List  (0) 2018.03.20
반응형


+클래스 

class 클래스명:
     def __init__(self, 파라미터,...):
          ...
     def 메서드1(self, 파라미터,...):
          ...
__init__ ; 생성자

__del__ ; 소멸자


class Man:
     def __init__(self, name):
          self.params={}
          self.name=name
          print("aa")
    
     def hi(self):
          print("hi "+self.name+"!")
     
     def setAge(self, a):
          self.params['age']=a

    def __del__(self):
          pass

m=Man("jj")          # 생성자 호출!  
m.hi()
del m          # m객체 소멸. 소멸자 호출!
-------------------------------------------------------------------------

class SumClass:
     def __init__(self, name):     // constructor
          self.name=name 
     def sum(self, a, b ):     // 첫번째 인자는 self로 해야 한다.
          result=a+b
a = SumClass("jane')
a.sum(1,2)

-------------------------------------------------------------------------------

class Fib:
     '''iterator that yields numbers in the fibonacci sequence'''

     def __int__(self, max):
          self.max = max          #     instance에서의 global 변수. self.*
     def __iter__(self):
          self.a=0
          self.b=1
          return self
     def __next__(self):
          fib = self.a
          if fib > self.max:
               raise StopIteration
          self.a, self.b = self.b, self.a+self.b
          return fib

빈 클래스 정의시, 문법적 오류를 피하기 위해 내용에 pass 라고 쓴다. 나중에 작업할 때 사용.

class PapayaWhip:
     pass


+클래스의 객체 생성 ; 클래스명(constructor)으로 함수 호출처럼 한다.

f = Fib(100)
for i in f :
    print( i, end=“ “)
에러없이 마지막까지 출력된다.




+ 클래스 상속  ; 클래스 선언시 뒤에 (parent) 를 추가한다.

class B(A):
    pass

A클래스로부터 상속받는다.

ex)
class Person:
    def __init__(self, name, age, gender):
          self.Name = name
          self.Age= age
          self.Gender = gender
    def aboutme(self):
          pass
class Employee(Person):
     def __init__(self, name, age, gender, salary):
          super().__init__(self, name, age, gender)     # Person._init__(..)을 사용해도 되나, 다중상속시 중복실행되는 것을 막기위해 super를 사용한다.
         self.Salary=salary
    def work(self):
          pass

   
+ 다중 상속도 지원한다.
class Child(ParentOne, ParentTwo):
..




+ 연산자 오버로딩

아래와 같이 미리 정의된 함수를 중복 정의하여 사용한다.

__add__(self, other)
__mul__(self, other)
__sub__(self, other)
...

피연산자의 순서가 뒤바뀐 경우도 지원하려면?
함수이름에 r을 붙인 것을 정의한다.
__add__=__radd__
__sub__=__rsub__
__mul__=__rmul__

n=numbox(100)
n+100
100+n



+ 클래스 메소드 class method   ; 첫 번째 인자가 cls 로 클래스를 의미.
@classmethod
def change_raise_amount(cls, rate):
     cls.raise_rate=rate
     

+static method     ; cls 객체가 없다.
@staticmethod
def is_work_day(day):
     return True



'Python' 카테고리의 다른 글

Python JSON 사용하기  (0) 2018.04.10
Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌6 tuple, set, dictionary  (0) 2018.03.21
Python 강좌5 List  (0) 2018.03.20
Python 강좌4 정규식 regular expression  (0) 2018.03.19
반응형


+ 튜플 (tuple)    ; immutable! 리스트와 같으나 변경불가.

() 를 사용한다. 리스트와 비슷하나, 튜플은 값을 변경할 수 없다.
t1=()
t2=(1,)             # 주의!!! 원소가 한 개인 경우 반드시 뒤에 ,를 써줘야 한다. 쓰지 않으면 () 연산자로 인식.
a,b = 10,20          # 이것도 튜플을 통한 복수 데이터 할당의 응용이다. 
b,a = a,b          # 이렇게 값을 동시에 변경할 수도 있다. swap이 쉽다.
t3=(1,2,3)
t4=1,2,3,4
위와 같이 사용

매크로 값 할당 처럼 사용 가능.
(MON, TUE, WED) = range(3)
MON=0
TUE=1
WED=2

-튜플 연산
+는 데이터 추가. *는 반복.
tuples=('a','b','c')
tuples+('d',e','f')     # a b c d e f 가 된다. 
tuples*3          # a b c a b c a b c가 된다.







+Set ; 집합.{}
노드들의 순서 없음. 중복은 추가되지 않음.
a_set = { 1 }

-list를 set으로 변환.
a_set=set(a_list)

a_set=set()        ; empty set
a_set.add(4)    ; item add
len(a_set)         ; item count
a_set.update( {4,5,6} )    ; items add (중복은 추가되지 않음.)
a_set.update( [10,20,30])    ; items add (중복은 추가되지 않음.)
a_set.discard( 10 )    ; 10을 삭제함. (없어도 에러 안남)
a_set.remove(10)    ; 10을 삭제함. (없으면 에러. KeyError)
a_set.clear()

30 in a_set    ; check (T/F) exist
a_set.union(b_set)    ; union set
a_set.intersection(b_set)    ; intersection
a_set.difference(b_set)    ; diff. A-B
a_set.symmetric_difference(b_set) ; diff.  (A+B)-(A intersect B)
a_set.issubset(b_set) ; T/F   check A<B
b_set.isupperset(a_set) ; T/F  check B>A











+ Dictionary
{key:value,...}를 사용.        json과 비슷.
unordered. key-value pairs.

dic={123:456, 3.14:11.2, (1,3):(3,1),  'abc':'def',  'list':{1,2,3}, 'dict':{1:2, 3:4}}

dic={'name':'pey', 'phone':'111111','birth':'1111'}
dic['name']
주의! 
a={1:'a',2:'b'}
a[1]='a' 이다.  Dictionary에서 a[1]에서 1은 인덱스가 아니고 Key다.!!

-사전에 추가 방법
a['name2']='test' ; 없으면 추가된다!!!.  있으면 업데이트된다. 
-삭제는 del을 사용!
del a['name2']
a.keys() ; key 명으로된 list
a.clear() ; 모두 삭제
a.get('name') ; 키로 값 얻기 ; a['name'] 과 동일하다.

-객체가 None 또는 empty이면 false로 취급.
-키가 없으면 KeyError 발생
a['akaka']

-사전 키 존재! 여부 검사 (in, has_key)
'name' in dic
True
'job' in dic
False

if 'keyname' in dic:
     use...
or
if dict.has_key('keyname')==1:
     use...
or
value=dic.get('keyname', 0)          # 키가 없으면 디폴트값으로 설정함.!! ( 널체크. null, None. )


+ dictionary 생성
import glob
import os
metadata_dict = { f:os.stat(f) for f in glob.glob('*test*.py') }

metadata_dict[0]
metadata_dict['atest01.py'].st_size
list(metadata_dict.keys())


+ key, value 뒤집기
{ value:key for key, value in a_dict.items() }


+ key, value 검색
for k, v in dictA.items():
     print(k,v)
for (k,v) in dictA.items(): 상동

for k in dictA:
     print(k, dictA[k])



'Python' 카테고리의 다른 글

Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌7 클래스  (0) 2018.03.27
Python 강좌5 List  (0) 2018.03.20
Python 강좌4 정규식 regular expression  (0) 2018.03.19
Python 강좌3 자료형. 수/문자열  (1) 2018.03.16

+ Recent posts